第六天第三个问题

发布时间 2023-04-18 20:19:12作者: 序章0

问题描述:

编写一个程序,它打开一个文本文件,逐个字符读取该文件,直到到达文件末尾,然后指出该文件有多少个字符。

解决思路:

1.先建立一个字符数组用于读取用户输入的文件名称

2.打印询问用户文件的名称

3.打开相应文件用cin逐个读取其中的字符,每读取一个就讲记录数加一,读取完成后关闭文件

4.输出记录数

代码:

#include <iostream>
#include <fstream>
using namespace std;
int main() {
int count = 0;
char filename[30];
ifstream infile;
cout << "enter the filename!" << endl;
cin >> filename;
infile.open(filename);
if (!infile.is_open()) {
cout << "could not open the file!\n";
exit(EXIT_FAILURE);
}
char ch;
infile >> ch;

while (infile.good())
{
count++;
infile >> ch;
}

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;
}