正常C代码如下:
#include <stdio.h>
void main()
{
char c;
int letter=0,space=0,digit=0,other=0;
printf("请输入一串字符,我们将统计各种字符的数量:\n");
while ((c=getchar()) != '\n')
{
if ((c>='a' && c<='z' || c>='A' && c<='Z'))
letter++;
else
if(c==' ')
space++;
else if(c>='0' && c<= '9')
digit++;
else
other++;
}
printf("字母=%d,空格=%d,数字=%d,其它=%d,\n",letter,space,digit,other);
}
想换成C++代码,改进如下过渡格式:
#include <iostream.h>
#include <stdio.h>
void main()
{
char c;
int letter=0,space=0,digit=0,other=0,flag=1;
cout << "请输入一串字符,我们将统计各种字符数量:" << endl;
while ((c=getchar()) != '\n')
{
if(c=='\n')
break;
if(c >= 'a' && c<= 'z' || c >= 'A' && c<= 'Z')
letter++;
else if(c== ' ')
space++;
else if(c>= '0' && c<='9')
digit++;
else
other++;
}
cout << "字母= " << letter << endl;
cout << "空格= " << space << endl;
cout << "数字= " << digit << endl;
cout << "其它= " << other << endl;
}
但并不是真正的C++代码,最终修改如下:
#include <iostream.h>
void main()
{
char c;
int letter=0,space=0,digit=0,other=0,flag=1;
cout << "请输入一串字符,我们将统计各种字符数量:" << endl;
cin >> c;
while ( c != '\n')
{
if(c=='\n')
break;
if(c >= 'a' && c<= 'z' || c >= 'A' && c<= 'Z')
letter++;
else if(c== ' ')
space++;
else if(c>= '0' && c<='9')
digit++;
else
other++;
cin >> c;
}
cout << "字母= " << letter << endl;
cout << "空格= " << space << endl;
cout << "数字= " << digit << endl;
cout << "其它= " << other << endl;
}
但并不能正常按回车返回,请各位看官求解. |