#include <stdio.h>
int main(void)
{
char ch;
int end=0;
printf("\nPick a letter a through f. (f ends the program)");
do
{
scanf("%c", &ch);
switch (ch) {
case 'a':
printf("a. another: ");
break;
case 'b':
printf("b. another: ");
break;
case 'c':
printf("c: another ");
break;
case 'd':
printf("d. another: ");
break;
case 'e':
printf("e. another: ");
break;
case 'f':
printf("f. Goodbye. ");
end=1;
break;
default:
printf("That wasn't a through f. ");
break;
}
} while (end == 0);
return 0;
}
因此,如果您输入a,则会说:
a. another: That wasn't a through f.
如果你输入说g,那么它会说:
That wasn't a through f. That wasn't a through f.
如果输入f则会按预期执行
f. Goodbye.
,程序终止。
有关如何解决此问题的任何提示?我已经尝试了一段时间,我得到的答案不是在C或他们说你忘了休息;声明。我是C的新手,所以也许这是显而易见的我没有注意到的,我也认为这可能是因为do while循环的东西?谢谢你的时间
答案 0 :(得分:3)
scanf("%c", &ch)
一次读取一个字符。如果您正在键入一个字母然后按Enter键,那么您将提供两个字符:字母和换行符(U + 000A,'\n'
)。
如果您想忽略换行符,一个选项是明确检查它们:
case '\n':
break;
答案 1 :(得分:0)
您也可以尝试使用此方法..
0 0 0 3 has 0 intersection
2 0 2 5 has 2 intersections
3 0 3 5 has 1 intersection
0 0 3 0 has 1 intersection
0 3 3 3 has 2 intersections
会自动吃掉多余的\ n个字符