good()

#include <iostream>
#include <fstream>
#include <string>

int main()
{
using namespace std;
const char filename[] = "t.txt";
ifstream fin;
string temp;

fin.open(filename);
if (!fin.is_open())
{
cout << "不能打开文件"<< filename << endl;
exit(EXIT_FAILURE);
}
int count = 0;
getline(fin, temp);
while (fin.good())
{
count++;
getline(fin, temp);
cout<<temp<<endl;
}
fin.close();
cout << "文件" << filename << "共有"
<< count << "行。\n";
return 0;
}
while(infile.good())//while input good and not at EOf
读文件时有几点你需要检查,首先程序文件不应超过EOF,如果到达文件尾返回true;程序也可能遇到类型不匹配的时候,若有不匹配fail()返回true;也有可能遇到意外的情况如恶文件损坏或硬件故障。如果最后一次读取文件时发生了这样的问题bad()返回true,分别检查这种情况用good(),个就是说good()也检查是否到达文件尾
在读完第四行后已到达文件尾了,所以count少加了一次楼主,我感觉这样修改一下比较好,
#include <iostream>
#include <fstream>
#include <string>

int main()
{
using namespace std;
const char filename[] = "t.txt";
ifstream fin;
string temp;

fin.open(filename);
if (!fin.is_open())
{
cout << "不能打开文件"<< filename << endl;
exit(EXIT_FAILURE);
}
int count = 1;
getline(fin, temp);
while (fin.good())
{

getline(fin, temp);
count++;
cout<<temp<<endl;
}
fin.close();
cout << "文件" << filename << "共有"
<< count << "行。\n";
return 0;
}
#include <iostream>
#include <fstream>
#include <string>

int main()
{
using namespace std;
const char filename[] = "t.txt";
ifstream fin;
string temp;

fin.open(filename);
if (!fin.is_open())
{
cout << "不能打开文件"<< filename << endl;
exit(EXIT_FAILURE);
}
int count = 0;

while ( getline(fin, temp))
{
count++;

cout<<temp<<endl;
}
fin.close();
cout << "文件" << filename << "共有"
<< count << "行。\n";
return 0;
}
为什么这样可以呢,使用good()是现在循环前(首次执行循环测试前)防止一跳输入语句,并在循环的末尾(下次执行循环测试前)放置一条输入放语句
infile>>value;
while(infile.good())
{
infile>>value;
}
鉴于这种事实可对上述代码进行精简:表达式infile>>value的结果为infi了,而在需要一个bool值得情况下infile的结果为infile.good(),即true或false
因此可以让两条输入语句用一条用作循环测试的输入语句代替。即:
while(infile>>value)
{
}
这种设计仍然遵循了在测试之前读取得规则,因为要计算表式ifile>>value的值程序必须首先将一个数字读取到value中
同理因为infile>>value是一个一个读的而getline()是一行一行读的,getline也适用

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值