2015-05-04 60 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