Unexpected behaviour of getline() with ifstream

我的梦境 提交于 2019-12-06 13:01:50

You are reading comma separated values so in sequence you read: 1, 2, 3\n4, 5, 6.

You then print the first character of the array each time: i.e. 1, 2, 3, 5, 6.

What were you expecting?

Incidentally, your check for eof is in the wrong place. You should check whether the getline call succeeds. In your particular case it doesn't currently make a difference because getline reads something and triggers EOF all in one action but in general it might fail without reading anything and your current loop would still process pStock as if it had been repopulated successfully.

More generally something like this would be better:

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

AFAIK if you use the terminator parameter, getline() reads until it finds the delimiter. Which means that in your case, it has read

3\n4

into the array pSock, but you only print the first character, so you get 3 only.

the problem with your code is that getline, when a delimiter is specified, ',' in your case, uses it and ignores the default delimiter '\n'. If you want to scan that file, you can use a tokenization function.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!