getstream()与ifstream的意外行为

Kam*_*ave 2 c++ csv getline istream

为了简化,我试图使用ifstream类及其getline()成员函数来读取CSV文件的内容.这是这个CSV文件:

1,2,3
4,5,6
Run Code Online (Sandbox Code Playgroud)

和代码:

#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;
}
Run Code Online (Sandbox Code Playgroud)

我期待读取所有数字,因为getline假定自上次读取后写入,并在遇到','或'\n'时停止.

但看起来它读取的一切都很好,除了'4',即第二行的第一个数字(参见控制台):

Iteration number 1
1
Iteration number 2
2
Iteration number 3
3
Iteration number 4
5
Iteration number 5
6
Run Code Online (Sandbox Code Playgroud)

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

(谢谢 !)

CB *_*ley 6

:所以在序列你读你正在阅读逗号分隔值1,2,3\n4,5,6.

然后,您打印每次数组的第一个字符:即1,2,3,5,6.

你有什么期待?

顺便提一下,您的支票eof是在错误的地方.您应该检查getline呼叫是否成功.在您的特定情况下,它目前没有区别,因为getline读取内容并在一个操作中触发EOF,但一般情况下它可能会在没有读取任何内容的情况下失败,并且您当前的循环仍将处理pStock,就像它已成功重新填充一样.

更普遍这样的事情会更好:

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