本题要求处理文件,所以必须加入fstream头文件,这个头文件中的ifstream和ofstream是用来打开和输出文件的,其中还有很多函数,在这里我用到了.open()、.is_open()、.good()、.eof()、.close()这几个函数。.open()函数是打开文件,比如.open("6.8.txt")就会打开名为“6.8.txt”的文件了;.is_open()函数时用来判断打开文件是否成功,例如.is_open("6.8.txt"),有可能是该程序的目录下找不到名为“6.8.txt”的文件,那么.is_open()函数就会返回false了;.good()函数是指读取成功;.eof()函数是用来判断是否读取到了最后;.close()函数是用来关闭打开的文件。这里我写的程序是请求用户输入文件名,这样该程序就可以用来打开任意文件,只要在该程序的目录下存在该文件就可以。
clude <iostream>
#include <fstream>
using namespace std;
int main() {
int count = 0;
char filename[30];
ifstream infile;
cout << "enter the filename!" << endl;
cin >> filename; //"carinfo.txt"
infile.open(filename);
if (!infile.is_open()) {
cout << "could not open the file!\n";
exit(EXIT_FAILURE);
}
char ch;
infile >> ch;
//infile.get(ch);
while(infile.good())
{
count++;
infile>>ch; //读取了68
//infile.get(ch);//读取了81;cin.get()读取包括空格、制表符、换行符;
}
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";
if (count == 0)
cout << "no data!\n";
else
cout << "count=" << count;
infile .close();
return 0;
}