C++:正在将CSV文件读取到结构数组中
C++: Reading CSV file into struct array
我正在进行一项任务,需要将未知行数的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/
相关文章:
- 将结构向量保存到文件中,并从C++文件中读取结构向量
- 从只读内存中读取结构
- 从包含 IP 标头片段的二进制文件中读取结构的最佳方法是什么
- 读取结构化文件
- CPP 在读取结构数据时无限循环错误?
- 打开文件以读取结构数组
- 无效操作数以二进制读取结构的阵列
- 读取结构数组时出错
- 如何从另一个类读取结构成员
- 读取结构 -- uint32 不命名类型
- 从流或字节中读取结构时遇到问题
- 读取结构C++二进制文件的运行时错误
- 从二进制文件读取结构数据时获取垃圾值
- 在 c++ 中向二进制文件写入/读取结构
- 在C++文件中写入和读取结构体的三维矢量
- C++按字段读取结构,并将结构直接写入流
- 从LISP的套接字中读取c++结构
- 读取结构化二进制文件c++
- C++二进制文件正在读取结构
- 从CArchive保存的二进制数据中读取结构数组