输入一个正整数 repeat (0
2
acm.zcmu.edu.cn/JudgeOnline ACMICPC.
AC Neng Nian Lai Guo Dao.
letter=30,blank=1,digit=0,other=5
letter=19,blank=5,digit=0,other=1
#include
int main()
{int n,letter,blank,other,digit;
scanf("%d",&n);
char c;
getchar();
while(n--!=0){letter=0;blank=0;other=0;digit=0;
while((c=getchar())!='\n'){
if(c>='a'&&c<='z'){letter++;
} else if(c>='A'&&c<='Z'){letter++;
} else if(c>='0'&&c<='9'){digit++;
} else if(c==' '){blank++;
} else{other++;
}
}
printf("letter=%d,blank=%d,digit=%d,other=%d\n",letter,blank,digit,other);
}
return 0;
}
这句的问题:while((c=getchar())!='\n') ,改用gets()函数 。修改如下,见注释,供参考:
#include<stdio.h>
int main()
{
int n, letter, blank, other, digit, i; //修改
scanf("%d", &n);
char c[256]; //修改
getchar();
while (n--) { //while (n-- != 0) 修改
letter = 0; blank = 0; other = 0; digit = 0; i = 0; //修改
gets(c); //修改
while(c[i]){
//while ((c = getchar()) != '\n') {
if (c[i] >= 'a' && c[i] <= 'z') {
letter++;
}
else if (c[i] >= 'A' && c[i] <= 'Z') {
letter++;
}
else if (c[i] >= '0' && c[i] <= '9') {
digit++;
}
else if (c[i] == ' ') {
blank++;
}
else {
other++;
}
i++;
}
printf("letter=%d,blank=%d,digit=%d,other=%d\n", letter, blank, digit, other);
}
return 0;
}
就这if...else还能超时?是不是要先输入完所有字符串,然后再统计输出啊?
因为最后一次输出可能没有换行符造成一直去getchar。
可以判断下c=='\n' || c == EOF时退出
试一下这个,不用两个while循环,只用一个for循环!
#include<stdio.h>
#include <stdlib.h>
#include <iostream>
#define N 999
int letter,blank,digit,other;
void count(char str[]){
letter=0,blank=0,digit=0,other=0;
for(int i=0;str[i]!='\0';i++){
if(str[i]>='A'&&str[i]<='Z')
letter++;
else if(str[i]>='a'&&str[i]<='z')
letter++;
else if(str[i]>='0'&&str[i]<='9')
digit++;
else if(str[i]==32)
blank++;
else
other++;
}
printf("letter=%d,blank=%d,digit=%d,other=%d\n",letter,blank,digit,other);
}
int main(){
char str[N];
int n;
scanf("%d",&n);
getchar();
for (int i=0;i<n;i++)
{
gets(str);
count(str);
}
}