水题,but为什么不是正确!!样例都是对的= =
(答案错误50%)
#include <stdio.h>
#include <algorithm>
#include <string>
#include <iostream>
using namespace std;
int main(){
string str[500];//i就是空格数
int i = 0,zimu = 0,qita = 0;
cin>>str[i];
while(getchar() == ' '){
i++;
cin>>str[i];
}
int num=0;
for(int j = 0;j <=i;j++){
for(int s=0;s <str[j].length();s++){
if(str[j][s]-'0' >=0 && str[j][s] -'0'<= 9){//判断是否为数字
num++;
}
else if(str[j][s]>='a'&&str[j][s]<='z' || str[j][s]>='A'&&str[j][s]<='Z'){//判断是否为字母
zimu++;
}
else{
qita++;
}
}
}
printf("%d %d %d %d",zimu,num,i,qita);
}
使用另一种写法,getline(cin,str);,可以包括空格读入str,通过了~
代码:
#include <stdio.h>
#include <algorithm>
#include <string>
#include <iostream>
using namespace std;
int main(){
string str;
getline(cin,str);
int num = 0,zimu = 0,kongge = 0,qita = 0;
for(int i = 0;i <str.length();i++){
if(str[i]-'0' >= 0 && str[i] -'0'<= 9){
num++;
}
else if(str[i]>= 'a' && str[i]<='z' || str[i]>='A' && str[i]<= 'Z'){
zimu++;
}
else if(str[i] == ' '){
kongge++;
}
else{
qita++;
}
}
printf("%d %d %d %d\n",zimu,num,kongge,qita);
}