按行读取 txt 并在 C++ 中通过逗号分隔

read txt by line and separate via commas in C++

我必须逐行读取 .txt 文件并用逗号分隔每行的内容,这样我才能用每一行创建一个对象。问题是,我发现了如何阅读每一行以及如何用字符(逗号、点、线等)分隔内容。问题是当我尝试一个与另一个实现时,一切都崩溃了。

最终结果应该是,如果在我有的文本中,例如:

135875,John,Smith
460974,Jane,Doe

我阅读了每一行,并用包含每个人信息的对象创建了一个链表,因此在阅读了每一行之后,我可以使用从 .txt

中提取的数据调用构造函数
user(int ID,String Name,String LastName);

你没有显示你的代码,所以我不知道你的代码有什么问题。但这里有一个代码片段,用于读取文件并执行您需要执行的操作。

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>

using namespace std;

int main()
{
    ifstream ifs("test.txt");
    string line;
    while (getline(ifs, line))
    {
        istringstream iss(line);
        int id;
        string tmp,name,lastname;
        getline(iss, tmp, ',');
        // stoi is only supported in c++11
        // Alternatively, you can use id = atoi(tmp.c_str());
        id = stoi(tmp);
        getline(iss, tmp, ',');
        name = tmp;
        getline(iss, tmp, ',');
        lastname = tmp;
        cout << "id: " << id << endl;
        cout << "name: " << name << endl;
        cout << "lastname: " << lastname << endl;
    }
    ifs.close();
    return 0;
}