尝试读取然后写入 csv 文件

Trying to read AND THEN write on csv file

我正在尝试从文件中读取内容,然后写入同一文件。 我有过这样的事情并且创造了奇迹:

int main() {

    fstream fp;

    string filePath = "test.csv";
    string outString;

    outString += "g1;1901;3;3;4;3;3;3;3\n";
    outString += ";1902;3;3;4;3;3;3;3\n";

    fp.open(filePath, ios::app | ios::in | ios::out);
    fp << outString;
    fp.close();
    return 0;
}

然后我有阅读部分,它读起来很好,但它不写:

int main() {

    fstream fp;
    string outString;
    string filePath = "test.csv";


    string line, csvItem;
    int numberOfGames = 0;

    fp.open(filePath, ios::app | ios::in | ios::out);
    if (fp.is_open()) {
        while (getline(fp, line)) {
            istringstream myline(line);
            while (getline(myline, csvItem, ';')) {
                cout << csvItem << endl;
                if (csvItem != "" && csvItem.at(0) == 'g') {
                    numberOfGames++;
                }
                else
                    break;
            }
        }
    }

    if (numberOfGames == 0) {
        outString = "Game;Year;AUS;ENG;FRA;GER;ITA;RUS;TUR\n";
    }

    outString += "g";
    outString += to_string(numberOfGames + 1);
    outString += ";1901;3;3;4;3;3;3;3\n";
    outString += ";1902;3;3;4;3;3;3;3\n";

    fp << outString;

    fp.close();


    return 0;
}

文件不存在则创建,否则读取。 阅读部分基于对这个问题的公认答案: Reading a particular line in a csv file in C++.

非常感谢!

到达文件末尾后,您会得到 fp.eof() == true。 如果检查 fp.tellg()(read/get 位置)和 fp.tellp()(write/put 位置)返回的值,您会发现它们此时是无效的。

您需要在到达 EOF 后和开始阅读之前重置流状态:

fp.clear();