代码段:
#include<bits/stdc++.h>
using namespace std;
int main()
{
ifstream ifile("date.txt", ios::in);
char s[100] = {0};
if (ifile)
{
int i = 0;
for (char c ; !ifile.eof(); ++i)
{
ifile>>c;
s[i] = c;
}
}
cout<<s<<endl;
return 0 ;
}
文件如下:
运行结果:
原因可能是ifile.eof()。
这样就好了:
#include<bits/stdc++.h>
using namespace std;
int main()
{
ifstream ifile("date.txt", ios::in);
char s[100] = {0};
if (ifile)
{
int i = 0;
for (; !ifile.eof(); ++i)
{
ifile>>s[i];
}
}
cout<<s<<endl;
return 0 ;
}
文件保持不变:
之前失败的原因:
1.最后一次循环写入到c失败了,c没有更新,还是把值传给s[i]了。
2.eof()读的是eofbit,这个东西在操作流的时候才会被置位。通俗来讲,你在里面读了一次数据,失败了之后才会给你置位。所以这个其实是访问上一次操作的状态。
也就是为什么之前的程序会重复输出了。
(向DL求助后得到答案)