输入一行字符,分别统计出其中英文字母、空格、数字和其他字符的个数
#include<iostream> using namespace std; int main(){ char c; int s=0,z=0,k=0,q=0; while((c=getchar())!='\n'){ int x=int(c); if(x>=48&&x<=57)s++; else if((x>=65&&x<=90)||(x>=97&&x<=122))z++; else if(x=32)k++; else q++; } cout<<"you have input "<<s<<" numbers"<<endl; cout<<"you have input "<<z<<" letters"<<endl; cout<<"you have input "<<k<<" spaces"<<endl; cout<<"you have input "<<q<<" some else chars"<<endl; return 0; }
上面那个代码,是我知道字符对应的ASCII码所以才那样写的。当然也可以这样写:
#include<iostream> using namespace std; int main(){ char c; int s=0,z=0,k=0,q=0; while((c=getchar())!='\n'){ int x=int(c); if(x>='0'&&x<='9')s++; else if((x>='A'&&x<='Z')||(x>='a'&&x<='z'))z++; else if(x=' ')k++; else q++; } cout<<"you have input "<<s<<" numbers"<<endl; cout<<"you have input "<<z<<" letters"<<endl; cout<<"you have input "<<k<<" spaces"<<endl; cout<<"you have input "<<q<<" some else chars"<<endl; return 0; }