简体   繁体   English

尝试读取然后在CSV文件中写入

[英]Trying to read AND THEN write on csv file

I'm trying to read something from a file and then write in the same file. 我正在尝试从文件中读取内容,然后写入同一文件中。 I had something like this and worked wonders: 我有这样的事情,并创造了奇迹:

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;
}

then I had the read part, it reads well but then it doesn't write: 然后我有了read部分,它读起来不错,但是没有写出来:

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;
}

The file is created if it doesn't exist, else, it is read. 如果文件不存在,则创建该文件,否则,将读取该文件。 The read part was based on the accepted answer to this question: Reading a particular line in a csv file in C++ . 读取的部分基于对该问题的公认答案: 在C ++中读取csv文件中的特定行

Thank you very much! 非常感谢你!

Once you reach the end of the file, you get fp.eof() == true. 到达文件末尾后,您将得到fp.eof()== true。 If you check the values returned by fp.tellg() (read/get position) and fp.tellp() (write/put position), you can see that they are invalid at that moment. 如果检查由fp.tellg()(读/获取位置)和fp.tellp()(写/放置位置)返回的值,则可以看到它们此时无效。

What you need is to reset the stream state once you reach EOF and before you start reading: 您需要的是一旦达到EOF并在开始阅读之前重置流状态:

fp.clear();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM