【问题标题】:C++: Reading CSV file into struct arrayC ++:将CSV文件读入结构数组
【发布时间】:2013-12-16 15:47:51
【问题描述】:

我正在处理一项任务,我需要将未知行数的 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

【问题讨论】:

    标签: c++ arrays file csv struct


    【解决方案1】:

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

    您可以使用file. clear() 将文件恢复到goid 状态。但是,仅此一项无济于事,因为流仍处于尽头。你可以在阅读之前从头开始,但我不会那样做。相反,我会一次性读取文件并将push_back() 每个元素读取到std::vector&lt;items&gt;

    请注意,您对每个 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);
    }
    

    究竟需要什么取决于确切的文件格式。

    【讨论】:

    • 我不知道它会在循环后停留在最后,所以感谢您的解释并感谢你们的时间。
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2013-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-11
      • 1970-01-01
      • 1970-01-01
      • 2021-02-13
      • 1970-01-01
      相关资源
      最近更新 更多