用c++写一个文本文件读取代码并统计文本文件的字符数
时间: 2024-05-13 09:20:35 浏览: 10
```
#include <stdio.h>
int main() {
FILE *fp;
char filename[50], ch;
int count = 0;
printf("Enter the filename: ");
scanf("%s", filename);
fp = fopen(filename, "r");
if (fp == NULL) {
printf("File does not exist.");
return 0;
}
while ((ch = fgetc(fp)) != EOF) {
count++;
}
printf("Total characters in file: %d", count);
fclose(fp);
return 0;
}
```
相关问题
统计文本文件中各类字符个数c++
以下是一个简单的C++程序,可以统计文本文件中各类字符的个数(包括字母、数字、空格、标点符号和其他字符):
```c++
#include <iostream>
#include <fstream>
using namespace std;
int main() {
char fileName[100];
cout << "请输入要统计的文件名:";
cin >> fileName;
ifstream inFile(fileName);
if (!inFile.is_open()) {
cout << "无法打开文件 " << fileName << "。" << endl;
return 1;
}
int counts[5] = {0}; // 分别统计字母、数字、空格、标点符号和其他字符的个数
char c;
while (inFile.get(c)) {
if (isalpha(c)) { // 判断是否为字母
counts[0]++;
} else if (isdigit(c)) { // 判断是否为数字
counts[1]++;
} else if (isspace(c)) { // 判断是否为空格
counts[2]++;
} else if (ispunct(c)) { // 判断是否为标点符号
counts[3]++;
} else { // 其他字符
counts[4]++;
}
}
inFile.close();
cout << "字母个数:" << counts[0] << endl;
cout << "数字个数:" << counts[1] << endl;
cout << "空格个数:" << counts[2] << endl;
cout << "标点符号个数:" << counts[3] << endl;
cout << "其他字符个数:" << counts[4] << endl;
return 0;
}
```
运行程序后,会提示用户输入要统计的文件名。程序会尝试打开这个文件,并逐个读取其中的字符,根据字符的种类统计各类字符的个数。最后输出结果。
需要注意的是,以上程序只能统计ASCII码字符的个数,对于Unicode字符可能需要使用其他方法。
统计文本文件中字母、数字及其他字符个数c++
可以使用C++中的文件输入输出流和字符处理相关函数来实现统计文本文件中字母、数字及其他字符个数的功能。
下面是一份示例代码:
```c++
#include <iostream>
#include <fstream>
#include <cctype>
using namespace std;
int main()
{
string filename;
cout << "请输入文件名(包括路径):" << endl;
cin >> filename;
ifstream infile(filename.c_str());
if(!infile)
{
cout << "文件打开失败!" << endl;
return -1;
}
char ch;
int letter_count = 0, digit_count = 0, other_count = 0;
while(infile.get(ch))
{
if(isalpha(ch))
letter_count++;
else if(isdigit(ch))
digit_count++;
else
other_count++;
}
cout << "字母个数:" << letter_count << endl;
cout << "数字个数:" << digit_count << endl;
cout << "其他字符个数:" << other_count << endl;
infile.close();
return 0;
}
```
运行程序后,输入待统计的文件名,程序会打开文件并读取其中的字符。使用isalpha函数判断字母,isdigit函数判断数字,其他字符即为其他类型。
最后输出统计结果,并关闭文件。