无论输入什么只有other会改变,其他三个不变无论输入什么只有other会改变,其他三个不变
if((c=getchar()) != '\n')
等于的优先级低于不等于判断,所以你的写法实际是先判断getchar() != '\n',然后将判断结果赋值给c。这样c只会是0或1了
应该是while循环判断那里表达式的问题,因为等号=的优先级比不等于优先级低,所以先执行getchar()!='\n' ,在读取输入的字符遇到换行符前getchar()!='\n' 这个的值都是1,即输入的字符都不是换行符,然后把这个1赋值给字符变量c,所以while循环里面,c的值都为1,就只有else那里满足,所以就会只有other的值发生改变。
解决办法是,c=getchar()!='\n'改为(c=getchar())!='\n',就是先把getchar()读取的字符赋值给c,然后再判断是否是换行符。
修改如下:
#include <stdio.h>
int main(void){
int letter=0,space=0,digit=0,other=0;
char c;
printf("请输入一个字符串:\n");
while((c=getchar())!='\n'){
printf("%d ",c);
if(c>='a'&&c<='z'||c>='A'&&c<='Z'){
++letter;
}else if(c==' '){
++space;
}else if(c>='0'&&c<='9'){
++digit;
}else{
++other;
}
}
printf("\n");
printf("letter=%d\nsapce=%d\ndigit=%d\nother=%d\n",letter,space,digit,other);
return 0;
}