[英]C++: How to read csv file with newline and comma delimited
I'm aware that this question has been asked.我知道有人问过这个问题。 But I couldn't find a solution for my case.
但是我找不到适合我的案例的解决方案。 I have a file as follow:
我有一个文件如下:
4
apple,banana,cat,donkey
My desired output is this:我想要的输出是这样的:
apple|banana|cat|donkey|
And my code:还有我的代码:
ifstream infile;
infile.open("file1.txt");
int num;
string line;
infile >> num;
infile >> line;
size_t pos = 0;
vector<string>data;
string a;
while ((pos = line.find(",")) != string::npos){
a = line.substr(0, pos);
data.push_back(a);
line.erase(0, pos + (",".length()));
}
for (auto x: data)
cout << x << "|";
By finding comma, I managed to read first 3 items, but failed to read the last one (donkey).通过找到逗号,我设法阅读了前 3 项,但未能阅读最后一项(驴)。 How can I detect the newline with a similar method, preferably without getline?
如何使用类似的方法检测换行符,最好不要使用 getline? It failed when I use newline as delimiter.
当我使用换行符作为分隔符时它失败了。
Add the condition after the loop在循环后添加条件
if (!line.empty())
data.push_back(line);
This will add the tail after the last comma to the vector.这会将最后一个逗号后的尾部添加到向量中。
New line is not placed at the end of the line when you read a string from an input stream like ifile >> line;
当您从输入流(如
ifile >> line;
读取字符串时,不会在行尾放置新ifile >> line;
. .
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.