· 必须包含头文件<fstream>
· 头文件定义了一个用于处理输入的ifstream类
· 需要声明一个或多个ifstream变量(对象)
· 必须指明名称空间std
· 需要将ifstream对象与文件关联起来。使用方法之一是open()
· 使用完文件后,应使用close()方法将其关闭
· 可结合使用ifstream对象和运算符>>来读取各种数据类型
· 可以使用ifstream对象和get()方法来读取一个字符,使用ifstream对象和getline()来读取一行字符
· 可以结合使用ifstream和eof()、fail()等方法来判断输入是否成功
· ifstream对象本身被用作条件测试时,如果最后一个字符读取成功,它将被转换为bool值true,否则被转换为false
#include<iostream>
#include<fstream>
#include<cstdlib> // support for exit()
int main()
{
using namespace std;
char filename[100] = "test.txt";
ifstream inFile.open(filename);
if (!inFile.is_open())
{
cout << "Could not open!" << endl;
exit(EXIT_FAILURE);
}
double value, sum = 0; int count = 0;
inFile >> value;
while (inFile.good()) // while input good and not at EOF
{
++count; sum += value;
inFile >> value;
}
if (inFile.eof()) cout << "End of file reached.\n";
else if (inFile.fail())
cout << "Input terminated by data mismatch.\n";
else cout << "Input terminated for unknown reason.\n";
cout << "sum: " << sum << " count: " << count << endl;
inFile.close();
return 0;
}
说明:
eof():如果最后一次读取数据时遇到EOF,返回true,否则返回false
fail():如果最后一次读取操作中发生了类型不匹配的情况,返回true(遇到了EOF,该方法也返回true),否则返回false
good():在没有任何错误时返回true,否则返回false
代码简化:
表达式inFile >> value的结果为inFile,而在一个需要bool值的情况下,inFile的结果为inFile.good(),即true或false
while (inFile >> value) // read and test for success
{
// loop body here goes
// omit end-of-loop input
}