我被要求编写一个执行某项任务的程序,如果用户输入“' y”,该程序会自行重复。或者如果用户输入' n'在任务结束时。为了简单起见,让我们说它要打印的任务"有一个美好的一天"。 这是我的代码:
int main(void) {
char cont;
bool repeat = true;
while (repeat == true){
printf("Have a nice day!\n");
printf("continue to print?\n");
scanf("%c",&cont);
if (cont == 'n') {repeat = false;}}
}
然而,输出似乎不正确。进入' y'后的实际输出两次,然后' n'一次是
Have a nice day!
continue to print?
y
Have a nice day!
continue to print?
Have a nice day!
continue to print?
y
Have a nice day!
continue to print?
Have a nice day!
continue to print?
n
反对
Have a nice day!
continue to print?
y
Have a nice day!
continue to print?
y
Have a nice day!
continue to print?
n
所以基本上每次' y'输入,消息打印两次而不是一次。知道我哪里做错了吗?
答案 0 :(得分:2)
scanf("%c",&cont);
应该是
scanf(" %c",&cont);
在第一次输入结束时有一个换行符,并且在下一次迭代中被%c
选中。请注意%c
之前占用换行符