#include<iostream>
#include<cctype>
#include<cstdlib>//support for exit(),atoi()
#include<string>
#include<fstream>//文件I/O
#include<sstream>//stringstream转换各种数据格式
using namespace std;
void main()
{
<span style="white-space:pre"> </span>ifstream infile;
<span style="white-space:pre"> </span>infile.open("1.txt");
<span style="white-space:pre"> </span>if(!infile.is_open())
<span style="white-space:pre"> </span>{
<span style="white-space:pre"> </span>cout<<"Could not open the file."<<endl;
<span style="white-space:pre"> </span>cout<<"Program terminating."<<endl;
<span style="white-space:pre"> </span>exit(EXIT_FAILURE);
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>int count=0;
<span style="white-space:pre"> </span>char ch;
<span style="white-space:pre"> </span>while(infile.good())
<span style="white-space:pre"> </span>{
<span style="white-space:pre"> </span>infile>>ch;
<span style="white-space:pre"> </span>count++;
<span style="white-space:pre"> </span>cout<<ch;
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>cout<<endl;
<span style="white-space:pre"> </span>if(infile.eof())
<span style="white-space:pre"> </span>cout<<"End of file reached."<<endl;
<span style="white-space:pre"> </span>else if(infile.fail())
<span style="white-space:pre"> </span>cout<<"Input terminated by data mismatch.\n";
<span style="white-space:pre"> </span>else //这个else是包含在上一个else里面的
<span style="white-space:pre"> </span>cout<<"Input terminated for unknown reason.\n";
//<span style="white-space:pre"> </span>if(count==o)
//<span style="white-space:pre"> </span>cout<<"No data processed.\n";
<span style="white-space:pre"> </span>cout<<"该文件中包含了"<<count<<"个字符"<<endl;
<span style="white-space:pre"> </span>infile.close();//使用完文件后要将文件关闭
}
C++primer plus第六版课后编程练习答案6.8
最新推荐文章于 2021-06-02 22:06:03 发布