当拥有倍数数据类型C 时,正确读取文件末尾的方法
Proper way to read to the end of file when having multiples data types c++
我制作了一个简单的程序,可以计算出售商品的价格。并将信息保存到一个文件中。我正在尝试从包含字符串和整数的文件中读取。读取文件末尾的好方法是什么?我目前正在使用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
,您会发现自己的错误。
相关文章:
- 正在将csv文件读取为双精度矢量
- 将从格式化文本文件读取的文本数据存储到链表
- C++ 读取文件读取文件不正确
- 使用对象文件读取三角形数据网格
- 如何减慢从 BVH 文件读取的 opengl 动画?
- 从文件读取,并写入函数C++中的数组
- 从对象C++中的文件读取内容时出现分段错误
- 从文件读取并通过矢量输出到控制台
- 尝试将字符串从文件读取到无符号字符向量中
- 如何将文本文件读取到二维数组中并以 c++ 打印
- 简化文件读取的函数
- 如何将逗号分隔的文件读取为 2D int 数组?
- 在 c++ 中将数据从文件读取到队列中
- 'std::wstring_convert'尽可能多地转换(从 UTF8 文件读取块)
- C++,从文件读取到结构,然后读取到向量(结构被推入向量太多次,而不仅仅是一次)
- 文件读取C++包括空格键
- 从文件读取时未将值推回矢量
- 从文件 C++ 读取时的无限循环
- 从同一文件读取和写入?
- 从.txt文件读取到C++中的双精度向量