请教一个关于ifstream的问题

ding525 2008-10-22 11:04:14
下面的程序,urls.txt的内容只有四行,为什么程序最后打印出5来?
#include <fstream>
#include <iostream>
using std::ifstream;
using std::cout;
using std::endl;

int main()
{
int i=1;
ifstream inputFile("c:\\urls.txt");
while (! inputFile.eof())
{
cout << i++ << endl;
}
}
...全文
65 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
test4ever 2008-10-22
  • 打赏
  • 举报
回复
楼上们
请注意
cout<<i++ << endl
是先输出流,再++
test4ever 2008-10-22
  • 打赏
  • 举报
回复

#include <fstream>
#include <iostream>
using std::ifstream;
using std::cout;
using std::endl;

int main()
{
int i=1;
ifstream inputFile("d:\\urls.txt");
while(!inputFile.eof())
{
cout << inputFile.get()<<"\t"<<i++ << endl;
}
getchar();
}


测试这段代码
结束符占一位,所以比你预计的多一个
elegant87 2008-10-22
  • 打赏
  • 举报
回复
把i的初始值设置为0!
开心爸爸84 2008-10-22
  • 打赏
  • 举报
回复
int i=0;
yeah920 2008-10-22
  • 打赏
  • 举报
回复
帮忙顶。
hurryboylqs 2008-10-22
  • 打赏
  • 举报
回复
因为i++
taodm 2008-10-22
  • 打赏
  • 举报
回复
string a;
while (getline(inputFile, a))
{
cout <<a<<i++ << endl;
}

太乙 2008-10-22
  • 打赏
  • 举报
回复


#include <fstream>
#include <iostream>
using std::ifstream;
using std::cout;
using std::endl;

int main()
{
int i=1;
char a[100];
ifstream inputFile("1.txt");
while (! inputFile.eof())
{
inputFile.getline(a,100);
cout <<a<<i++ << endl;
}
}

----------------------------


output:

hello1
ddf2
fdsf3
fdsafsa4
Press any key to continue

太乙 2008-10-22
  • 打赏
  • 举报
回复


#include <fstream>
#include <iostream>
using std::ifstream;
using std::cout;
using std::endl;

int main()
{
int i=1;
char a[100];
ifstream inputFile("1.txt");
while (! inputFile.eof())
{
inputFile.getline(a,100);
cout <<a<<i++ << endl;
}
}

----------------------------


output:

hello1
ddf2
fdsf3
fdsafsa4
Press any key to continue

64,654

社区成员

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

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