关于输入输出文件流的问题
#include<iostream>
#include<fstream>
using namespace std;
void main()
{
ofstream fout("CSL2.txt");
if(!fout)
{
cout<<"Cannot open output file.\n";
exit(1);
}
fout<<100<<' '<<hex<<100<<endl;
fout<<"\"Hello\"\n";
fout.close();
ifstream fin("CSL2.txt");
if(!fin)
{
cout<<"Cannot open input file.\n";
exit(1);
}
char str[80];
while(fin)
{
fin.getline(str,80);
cout<<str<<endl;
}
fin.close();
}
我这里的while是怎么样进行的? fin.getline能读取空格。 那么我的CSL2.txt文件里由于在fout<<100<<' '<<hex<<100<<endl;有个endl那后面的空格岂不是在while循环里全部读取了??Hello后面的空格也是吗??
[解决办法]
100 64
"Hello"
你文件里的数据是上面那样的,是吧。
getline读一行,遇回车读取结束('\n'),后面没空格,没内容。。
楼主你要理解这里行的意思。
楼主跑下下面这个代码,体会一下:
- C/C++ code
#include<iostream>#include<fstream>using namespace std;void main(){ ofstream fout("CSL2.txt"); if(!fout) { cout<<"Cannot open output file.\n"; exit(1); } fout<<100<<' '<<"\n"<<hex<<100<<endl<<" "; fout<<"\"Hello\"\n"; fout.close(); ifstream fin("CSL2.txt"); if(!fin) { cout<<"Cannot open input file.\n"; exit(1); } char str[80]; while(fin) { fin.getline(str,80); cout<<str<<endl; } fin.close();}