【发布时间】: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