2

为简化起见,我尝试使用 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

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

(谢谢 !)

4

3 回答 3

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++;
}
于 2010-08-18T10:54:25.173 回答
3

AFAIK 如果您使用终止符参数,getline()则读取直到找到分隔符。这意味着在您的情况下,它已阅读

3\n4

进入数组pSock,但你只打印第一个字符,所以你3只得到。

于 2010-08-18T10:51:50.153 回答
1

您的代码的问题是getline,当指定分隔符时,在您的情况下,','使用它并忽略默认分隔符'\ n'。如果要扫描该文件,可以使用标记化功能。

于 2010-08-18T10:56:35.193 回答