我使用getchar()来停止while字符串。我的问题是,如果我输入一个或两个字符,它会停止while字符串,如果用户输入的字符超过两个,则不会发生任何事情。
代码如下:
printf("enter srting\n");
while ((tmp=getchar()) !='\n') { \\here is my problem
count_letters++;
/* COUNTING WORD THAT START WITH LETTES L,A,C,H */
while (count_letters%3==0) {
switch (tmp) {
case 'A': count_a++;
break;
case 'C': count_c++;
break;
case 'H': count_h++;
break;
case 'L': count_l++;
default:
break;
}
} /* end of count letters while */
n1=n2;
n2=n3;
n3=tmp;
if (n1=='H' && n2=='Y' && n3=='A') {
count_hya++;
}
} /* end of getchar while */
printf("\n");
printf("%d", count_letters);发布于 2013-11-30 23:43:14
发布于 2013-11-30 23:41:19
以下是问题所在:
while (count_letters%3==0) {
switch (tmp) {
case 'A': count_a++;
break;
case 'C': count_c++;
break;
case 'H': count_h++;
break;
case 'L': count_l++;
default:
break;
}
}当您的第三个字符被读取时,您的程序由于(count_letters%3==0)而进入无限循环。
我不明白你代码的目的。我建议使用get()和字符串操作函数,因为您正在处理一整行。(请参阅string.h.h)
与get()+ for-loop相比,getchar()的效率也较低
https://stackoverflow.com/questions/20301897
复制相似问题