对文件流的操作问题

xqyangcsu 2004-05-07 10:47:41
各位大虾:
小弟很是迷惑阿!
下面这些代码:
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <iomanip>
#include <ctype.h>
#include <string>
using namespace std;
int main()
{
string name;
int price;
ifstream in;
in.open("merchantLog",ios::in);
if(!in)
{
cout<<"open file error"<<endl;
exit(1);
}

while(in)
{
in>>name;
cout<<setw(10)<<name;

in>>price;
cout<<setw(10)<<price<<endl;
}
in.close();
}

merchantLog文件中的内容:
box 78
pen 98
water 22
bread 9
wat 90
io 90
CD 99
DVD 990
book 45
Computer 8888
Mouse 100
mp3 999
coat 33
yxq 10000
d -1
为什么输出的结果中最后一行: d -1 输出两遍呢??
是不是流的缓冲区的问题呢?



...全文
51 4 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
xqyangcsu 2004-05-07
  • 打赏
  • 举报
回复
感谢freefalcon(心宇) 和 cngdzhang() 你们的解答使我茅塞顿开。谢谢!
freefalcon 2004-05-07
  • 打赏
  • 举报
回复
自己测了一下
while(in>>name>>price)
{
cout<<setw(10)<<name;
cout<<setw(10)<<price<<endl;
}
是可以的
因为只有当文件指针“超过”了文件末尾流状态才返回false
cngdzhang 2004-05-07
  • 打赏
  • 举报
回复
因为,流读完最后一个数据,还要再读一次in才返回0,但是这一次什么也没有读到,name和price保持不变

while(in)
{
in>>name;
cout<<setw(10)<<name;

in>>price;
cout<<setw(10)<<price<<endl;
}

改为:
in>>name;
in>>price;
while(in)
{
cout<<setw(10)<<name;
cout<<setw(10)<<price<<endl;
in>>name;
in>>price;
}
freefalcon 2004-05-07
  • 打赏
  • 举报
回复
试试:

while(in>>name>>price)
{
cout<<setw(10)<<name;
cout<<setw(10)<<price<<endl;
}

65,187

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧