gpt4 book ai didi

c++ - getline() 与 ifstream 的意外行为

转载 作者:太空狗 更新时间:2023-10-29 23:42:35 24 4
gpt4 key购买 nike

为简化起见,我尝试使用 ifstream 类及其 getline() 成员函数读取 CSV 文件的内容。这是这个 CSV 文件:

1,2,3
4,5,6

还有代码:

#include <iostream>
#include <typeinfo>
#include <fstream>

using namespace std;

int main() {
char csvLoc[] = "/the_CSV_file_localization/";
ifstream csvFile;
csvFile.open(csvLoc, ifstream::in);
char pStock[5]; //we use a 5-char array just to get rid of unexpected
//size problems, even though each number is of size 1
int i =1; //this will be helpful for the diagnostic
while(csvFile.eof() == 0) {
csvFile.getline(pStock,5,',');
cout << "Iteration number " << i << endl;
cout << *pStock<<endl;
i++;
}
return 0;
}

我希望所有的数字都被读取,因为 getline 应该获取自上次读取以来写入的内容,并在遇到 ',' 或 '\n' 时停止。

但它似乎能很好地读取所有内容,除了“4”,即第二行的第一个数字(参见控制台):

Iteration number 1
1
Iteration number 2
2
Iteration number 3
3
Iteration number 4
5
Iteration number 5
6

因此我的问题是:是什么让(我猜)'\n' 之后的这个 '4' 如此具体以至于 getline 甚至没有尝试考虑它?

(谢谢!)

最佳答案

您正在读取以逗号分隔的值,因此您按顺序读取:123\n456

然后每次打印数组的第一个字符:即 1235, 6

你在期待什么?

顺便说一下,您对 eof 的检查放错了地方。您应该检查 getline 调用是否成功。在您的特定情况下,它目前没有任何区别,因为 getline 读取了一些内容并在一个操作中触发了 EOF 但通常它可能会在不读取任何内容的情况下失败,并且您当前的循环仍会处理 pStock 就像重新填充成功一样。

更一般地说,这样的东西会更好:

while (csvFile.getline(pStock,5,',')) {
cout << "Iteration number " << i << endl;
cout << *pStock<<endl;
i++;
}

关于c++ - getline() 与 ifstream 的意外行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3511110/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com