(3)用键盘输入文件名,统计输出文件中每个字母、数字字符出现的次数;
代码
#include <iostream> #include <cstdlib> #include <fstream> #include <string> using namespace std; int main() { fstream infile; char textname[80]; gets(textname); infile.open(textname,ios::in); if(!infile) { cout<<"Can’t open the file."<<endl; abort(); } char buf[1000]; int i=1,ab=0,number=0; while(!infile.eof()) { infile.getline(buf,1000); for(i=0;buf[i]!='\0';++i) { if((buf[i]>='a'&&buf[i]<='z')||(buf[i]>='A'&&buf[i]<='Z')) ab++; else if(buf[i]>='0'&&buf[i]<='9') number++; } } cout<<"文件中"<<endl; cout<<"字母个数:"<<ab<<endl; cout<<"数字个数:"<<number; infile.close(); return 0; }
运行结果:
时间: 2024-10-26 22:05:36