我使用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);
答案 0 :(得分:1)
答案 1 :(得分:0)
问题在于:
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),您的程序进入无限循环
我无法理解您的代码的目的。 我建议使用gets()和字符串操作函数,因为您正在处理整行。 (见string.h)
与gets()+ for-loop 相比,getchar()的效率也较低