【问题标题】:Trying to read AND THEN write on csv file尝试读取然后写入 csv 文件
【发布时间】:2023-04-02 01:15:01
【问题描述】:

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

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++.

非常感谢!

【问题讨论】:

    标签: c++ csv read-write


    【解决方案1】:

    一旦到达文件末尾,就会得到 fp.eof() == true。 如果您检查 fp.tellg()(读取/获取位置)和 fp.tellp()(写入/放置位置)返回的值,您可以看到它们当时是无效的。

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

    fp.clear();
    

    【讨论】:

    • 非常感谢! :D
    猜你喜欢
    • 2017-10-22
    • 2016-04-27
    • 1970-01-01
    • 2022-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-20
    • 1970-01-01
    相关资源
    最近更新 更多