拜托,拜托,帮我看下这个程序,谢谢,谢谢
#include <iostream>
#include <fstream>
using namespace std;
void main()
{
ifstream inFile;
inFile.open( "file.txt ",ios::in);
if( !inFile )
cout < < "can 't open " < < endl;
char ch = '\0 ';
while( !inFile.eof() )
{
inFile.get(ch);
cout < < ch < < endl;
}
inFile.close();
}
#include <iostream>
#include <fstream>
using namespace std;
void main()
{
ifstream inFile;
inFile.open( "file.txt ",ios::in);
if( !inFile )
cout < < "can 't open " < < endl;
char ch = '\0 ';
while( inFile.get(ch) )
{
cout < < ch < < endl;
}
inFile.close();
}
两个程序都是在VC++6.0下编译运行的,可是读出来的结果却不一样.
我的file.txt文件中的内容是 12
但是运行出来的结果第一个是: 1 2 2,而第二个是:1 2
为什么会不一样,请大侠帮我解释一下,我实在看不出这两个算法到底有什么区别,第一个算法中,为什么明明已经读到2了,但是inFile.eof() 依然是假,谢谢了,
[解决办法]
while( !inFile.eof() )
{
inFile.get(ch);
cout < < ch < < endl;
}
你从文件中读取到2后,eof的标志并没有被设置,所以会继续循环,所以多输出了一个2
改成
inFile.get(ch);
while( !inFile.eof() )
{
cout < < ch < < endl;
inFile.get(ch);
}
[解决办法]
对于
while( inFile.get(ch) )
{
cout < < ch < < endl;
}
当你读到2,获取下一个字符失败,循环就不会在执行,所以输出结果正常