当拥有倍数数据类型C 时,正确读取文件末尾的方法

Proper way to read to the end of file when having multiples data types c++

本文关键字:文件 读取 方法 拥有 数据类型      更新时间:2023-10-16

我制作了一个简单的程序,可以计算出售商品的价格。并将信息保存到一个文件中。我正在尝试从包含字符串和整数的文件中读取。读取文件末尾的好方法是什么?我目前正在使用EOF函数,但无法正常工作。它重复最后两行。

 void viewTransactions();
 void viewTransactions()
{
    string productName,;
    int quantity, totalPrice;
    ifstream infile;
    infile.open ("transactions.txt");
    while(!infile.eof())
    {
    getline(infile, productName);
    infile >> quantity;
    infile >> totalPrice;
    infile.ignore(100, 'n');
    cout << productName << endl;
    cout << quantity << endl;
    cout << totalPrice << endl;

    }
}

" transactions.txt"包含:

Product
1
5
Product
2
10
Product
3
15

读取时控制台输出文件:

Product
1
5
Product
2
10
Product
3
15
3
15

infile. eof()在读取操作之后仅有效(不是"之前")。std::getline可以设置eofbit,因此更好的代码:

for(;;) {
  getline(infile, productName);
  if (infile.eof()) break;
  infile >> quantity;
  infile >> totalPrice;

等...(或使用do ... while(!infile.eof())循环)。

有一个原因(至少在POSIX上,例如Linux):在OS级别上没有办法(即使用Syscalls(2)中列出的系统调用(即使用Syscalls(2))来神奇地测试EOF条件,这是结果某些以前的读(2)操作。

顺便说一句,您可能应该使用所有警告和调试信息(带有GCC的g++ -Wall -Wextra -g)进行编译。然后使用调试器gdb ,您会发现自己的错误。