C ++处理文件,无法编写程序

时间:2016-12-31 21:13:32

标签: c++

我正在尝试创建一个可以将数据连续添加到.txt文档的简单程序。看看我的代码:

#include <iostream>
#include <fstream>

using namespace std;

int main () {
    ofstream playersW("players.txt");
    ifstream playersR("players.txt");

    int id;
    string name, info = "";
    float money;

    while (playersR >> id >> name >> money) {
        if (playersR.is_open()) {
            info += to_string(id) + " " + name + " " + to_string(money) + "\n";
        }
    }

    playersW << info;

    playersR.close();

    cout << "Enter player ID, Name and Money (or press 'CTRL+Z' + 'Enter' to quit):" << endl;

    while (cin >> id >> name >> money) {
        if (playersW.is_open()) {
            playersW << id << " " << name << " " << money << endl;
        }
    }

    playersW.close();
}

我想要的是首先读取存储在 players.txt 中的数据,然后再次写入并将新的附加数据添加到 players.txt

编辑:根据我现在的代码,我的程序在文件 players.txt 中写入用户输入的新信息

1 个答案:

答案 0 :(得分:1)

这是一个简单的程序,可以在二进制模式下打开文件players.txt,因此它首先读取内容并显示它,然后它要求用户输入新的播放器,直到用户输入0或否定播放器id因此循环中断然后关闭文件以保存新的附加内容:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main ()
{

    fstream players("players.txt");

    int id;
    string name, info = "";
    float money;

    while (players >> id >> name >> money)
        cout << name << "   " << id << "   "  << money << endl;

    players.clear();
    players.seekp(0, ios::end);

    cout << "Enter player ID, Name and Money (or press 'CTRL+Z' + 'Enter' to quit):" << endl;

    while(1)
    {
        cout << "id: "; 
        cin >> id;
        cout << endl;

        if(!cin || id <= 0)
            break;

        cout << "name: ";
        cin >> name;
        if(!cin)
            break;
        cout << endl;

        cout << "money: ";
        cin >> money;
        if(!cin)
            break;
        cout << endl;

        players << id << "   " << name << "   " << money << endl;
    }

    players.close();

    return 0;
}