#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也适用