2015-05-04 27 views
0

比方说,我写这一段代码:不期望的双重复

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循环时,发生了同样的事情。

+3

如果您不想让它们重复,请将打印件移出循环! – pmg

+7

试试这个'scanf(“%c”,&c);' – haccks

+0

@haccks它很有效!非常感谢!你能解释为什么吗?这个圆括号里面的空间对我来说是个谜! – George

回答

0

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

0

用户输入不正确的字符后,标准输入缓冲区中仍然存在(至少)换行符。

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

+0

“...直到收到EOF。”嗯,怀疑你想要,直到' '\ n''或'EOF'收到。 – chux