C++:正在将CSV文件读取到结构数组中

C++: Reading CSV file into struct array

本文关键字:读取 结构 数组 文件 CSV C++      更新时间:2023-10-16

我正在进行一项任务,需要将未知行数的CSV文件读取到结构化数组中。只能通过C++,而不是C(他们不希望我们两者结合)。

所以,我有以下代码:

// DEFINITION
struct items {
    int ID;
    string name;
    string desc;
    string price;
    string pcs;
};
void step1() {
    string namefile, line;
    int counter = 0;
    cout << "Name of the file:" << endl;
    cin >> namefile;
    ifstream file;
    file.open(namefile);
    if( !file.is_open()) {
        cout << "File "<< namefile <<" not found." << endl;
        exit(-1);
    }
    while ( getline( file, line) ) { // To get the number of lines in the file
        counter++;
    }
    items* item = new items[counter]; // Add number to structured array
    for (int i = 0; i < counter; i++) {
        file >> item[i].ID >> item[i].name >> item[i].desc >> item[i].price >> item[i].pcs;
    }
    cout << item[1].name << endl;
    file.close();
}

但当我运行代码时,应用程序会在阅读后返回空间,我实际上认为它根本没有阅读。这是控制台中的输出:

Name of the file:
open.csv
Program ended with exit code: 0

您的第一个循环读取流。当没有其他内容可供阅读时,它就会停止。在这一点上,流进入故障模式(即std::ios_base::failbit被设置),并且它将拒绝读取任何内容,直到它以某种方式被恢复。

您可以使用file. clear()将文件恢复到goid状态。然而,单凭这一点并没有帮助,因为这条小溪仍在尽头。你可以在阅读前先找到开头,但我不会那样做。相反,我会一次性读取文件,并将每个元素的push_back()读取为std::vector<items>

请注意,您为每个items记录提供的输入可能不完全符合您的要求:如果您真的有一个CSV文件,则需要读取到分隔符(例如,),并在读取ID后忽略分隔符。此外,您应该始终在读取后测试流的状态。你的循环可能看起来像这样:

for (items i;
      (file >> i.id).ignore(std::numeric_limits<std::streamsize>::max(), ',')
      && std::getline(file, i.name, ',')
      && std::getline(file, i.desc, ',')
      && std::getline(file, i.price, ',')
      && std::getline(file, i.pcs); ) {
    is.push_back(i);
}

具体需要什么在某种程度上取决于确切的文件格式。

您的文件指针位于while循环之后的文件末尾,以确定行数。在我看来,你已经清除并重置了文件指针。此链接可能有助于您:http://www.cplusplus.com/forum/beginner/11564/