C++primer plus第六版课后编程练习答案6.8

#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();//使用完文件后要将文件关闭
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值