c++怎样实现读取txt文件里的字符串,并统计有多少个数字、大小写字母、空格、其他字符?

#include "stdafx.h"
#include "iostream.h"
#include "string.h"
int i=0,Ul=0,Ll=0,space=0,d=0,other=0;
void Read_file(char *filename)
{
char*p,s[30];

FILE *fp;
while(s[i]!='\0')
{
*p=s[i];
i++;

if(('A'<=*p)&&(*p<='Z'))
Ul++;
else if(('a'<=*p)&&(*p<='z'))
Ll++;
else if(('0'<=*p)&&(*p<='9'))
d++;
else if(*p==' ')
space++;
else
other++;
}

cout<<"大写字母:"<<Ul<<endl;
cout<<"小写字母:"<Ll<<endl;
cout<<"数字:"<<d<<endl;
cout<<"空格:"<<space<<endl;
cout<<"其它符号:"<<other<<endl;
fclose(fp);
}
int main(int argc, char* argv[])
{

Read_file("d:\\作业.txt");
return 0;
}

#include <fstream>
#include <iostream>
using namespace std;

const int rangeNum = 5; 
const int bufferSize = 256;
char buffer[bufferSize];
int range[rangeNum][2] = {{'A','Z'},{'a','z'},{'0','9'},{' ',' '},{0,256}};
char print[rangeNum][100] = {"大写字母","小写字母","数字","空格","其他"};
int ans[rangeNum];

int main() {
    ifstream fin("D:\\作业.txt");
    memset(ans,0,sizeof(ans));
    while ( fin.getline(buffer,bufferSize) ) {
          for (int i = 0; buffer[i] != '\0'; ++i) {
              int j;
              for (j = 0; j < rangeNum; ++j) {
                  if (range[j][0] <= buffer[i] && range[j][1] >= buffer[i]) {
                     break;
                  }
              } 
              ans[j]++;
          }
    }
    for (int i = 0; i < rangeNum; ++i) {
        cout << print[i] << ":" << ans[i] << endl;
    }
    fin.close();
    return 0;
}

追问

不错但看不懂哈哈

温馨提示:答案为网友推荐,仅供参考
相似回答