读取文件时,如何在使用 << 运算符后计算新行?

While reading form a file, how to account for new lines after using the << operator?

我无法从文件中将双精度值读入数组 在 for 循环的第一次迭代之后,由于换行符,没有更多的阅读。我怎样才能绕过这个问题?

输入文件示例:

2.55

word <---目前不会读

5.66

file.open("productsIn.txt");
   if(!file.is_open()){
    cout << "Could not open file." << endl;
    return 1;
}
 if(file.is_open()){
    cout << "file open" << endl;
    for(int i = 0; i < MAX_COUNT; i++){
        getline(file, productName[i]);
        file >> prices[i];
        if(file.good()){
            cout << productName[i] << endl << prices[i] << endl;
        }
    }
 }
    file.close();

如果您的数据由交替的名称和价格行组成,如下所示:

item 1
1.50
item2
2.50
...

您当然可以在阅读浮动后简单地调用另一个 getline()。它会读出读取位置的换行符,并清除可以忽略的虚拟字符串参数。这是有道理的,因为你读了两行,所以你可能需要两个 getline。 (您 可以 在名称后不使用 getline() 因为价格的格式化输入将跳过空格;但我猜 EOL 是 "end of name" 的标记,其中一个名称可能由多个单词组成。)

您也可以按照 this complete answer 中的建议使用 ignorews

因为数据实际上是面向行的,所以遵循 Pete Becker 的建议并通过 getline() 读取所有行可能会更清楚,解析需要它的行——比如价格——只需通过 [i]stringstream.