C中不需要的重复重复

时间:2015-05-04 17:26:31

标签: c loops do-while repeat

让我们说我正在编写这段代码:

char c; // c from choise.
do{
    printf("Please choose one of the following operators:\n"); 
    printf("+ for Addition\n- for Subtraction\n* for Multiplication\n/ for Division\n");
    printf("= for Assignment and\nE to check if two variables have the same type and value.\n");
    scanf("%c", &c);
}while(c!='+' && c!='-' && c!='*' && c!='/' && c!='=' && c!='E');

主要问题是,当用户插入数字或字母时,除了上述操作符之外的其他所有内容,printf内的每条消息都会在屏幕上显示两次。

例如,如果c =' A'我们有:

Please choose one of the following operators:
+ for Addition
- for Subtraction
* for Multiplication
/ for Division
= for Assignment and
E to check if two variables have the same type and value.
A //wrong answer, the loop continues...
Please choose one of the following operators:
+ for Addition
- for Subtraction
* for Multiplication
/ for Division
= for Assignment and
E to check if two variables have the same type and value.
Please choose one of the following operators:
+ for Addition
- for Subtraction
* for Multiplication
/ for Division
= for Assignment and
E to check if two variables have the same type and value.
//here the program awaits the new value of c.

但是,如果c =' - '或者c =' +'等等,我们当然有

Please choose one of the following operators:
+ for Addition
- for Subtraction
* for Multiplication
/ for Division
= for Assignment and
E to check if two variables have the same type and value.
- // or +
//the program goes to the next line.

当我尝试在while或for循环中转换do_while循环时发生了同样的事情。

2 个答案:

答案 0 :(得分:0)

用户键入错误字符后,stdin缓冲区中仍然存在(至少)换行符。

@haccks的评论是解决问题的一种方法。 另一种方法是通过调用getchar的短循环来跟踪scanf,直到收到EOF。

答案 1 :(得分:0)

%c之前添加空格:scanf(" %c", &c);。这是因为从先前输入中输入的换行符可能存储在c中。
您也可以在getchar()之后使用scanf()清除输入缓冲区。