c++输入一行字符,怎样分别统计出其中英文字母,空格,数字字符和其它字符的个数?

用cin.get(c)函数从键盘上输入一个字符给变量c,直到输入回车换行字符'\n'为止。

#include <iostream>

using namespace std;

int main()

{

char c;

int el=0,sp=0,nu=0,other=0; 

while(cin.get(c))

{

if(c=='\n')

break;

if((c>='A' && c<='Z')||(c>='a' && c<='z'))

el++;

else if(c>='0'&&c<='9')

nu++;

else if(c==' ')

sp++;

else 

other++;

}

cout<<"英文字母个数="<<el<<endl<<"数 字 个 数 ="<<nu<<endl<<"空 格 字 数 ="<<sp<<endl<<"其他字符个数="<<other<<endl;

system("pause");

return 0;

}

温馨提示:答案为网友推荐,仅供参考
第1个回答  2018-01-06

#include &lt;iostream&gt;
using namespace std;
int main()

{
char c;
int el=0,sp=0,nu=0,other=0; 
while(cin.get(c))

{
if(c=='\n')
break;
if((c&gt;='A' && c&lt;='Z')||(c&gt;='a' && c&lt;='z'))
el++;
else if(c&gt;='0'&&c&lt;='9')
nu++;
else if(c==' ')
sp++;
else 
other++;
}

cout&lt;&lt;"英文字母个数="&lt;&lt;el&lt;&lt;endl&lt;&lt;"数 字 个 数 ="&lt;&lt;nu&lt;&lt;endl&lt;&lt;"空 格 字 数 ="&lt;&lt;sp&lt;&lt;endl&lt;&lt;"其他字符个数="&lt;&lt;other&lt;&lt;endl;
system("pause");
return 0;

}
<a href="https://iknow-pic.cdn.bcebos.com/2fdda3cc7cd98d10d7509b23233fb80e7bec9018?x-bce-process=image/quality,q_85" ><img src="https://iknow-pic.cdn.bcebos.com/2fdda3cc7cd98d10d7509b23233fb80e7bec9018?x-bce-process=image/resize,m_lfit,w_450,h_600,limit_1/quality,q_85"></a>

相似回答