[英]this function run too many times
為什么我還要寫其他字母或數字(不是y \\ n)的訂單
printf("\nWould you like to play again? (y/n):");
跑兩次?
int ans= 0,i=1;
do
{
printf("\nWould you like to play again? (y/n):");
ans = getchar();
if (ans=='y')
{
printf("yyyyyyyyyyy");
i = i-1;
}
else if ( ans == 'n')
{
printf("nnnnnnnnnnn");
i=i-1;
}
else
{
printf("not y or n");
}
}
while(i);
while(i)
實際上與while(i != 0)
。 如果輸入的不是y
或n
,則else
塊將運行,並且不會更改i
的值。 由於i=1
,所以在循環之前,如果您輸入的不是y
或n
,則i
不為零。 嘗試:
else
{
printf("not y or n");
i = i-1; // <---- new line
}
可能是因為您的getchar
呼叫正在從您的輸入中選擇換行符。 所以,如果你按“X”,第一次循環ans
是“X”和換行符被緩沖。 通過循環ans
的第二次是“ \\ n”。
您可以像這樣在輸入調用周圍放一個循環:
do
ans = getchar();
while (isspace(ans));
這太復雜了。 如您在評論中所述,您只想循環直到鍵入y
或no
。 不需要額外的變量。 通常,對於此類問題,使用計數器是個壞主意。 更安全的方法是使用bool
標志。
一個沒有幫助變量的好方法是:
int ans; // no need to initialise, as it is set before the first read
do {
printf("Play again?");
do {
ans = getchar();
} while ( ans == `\n` );
...
} while ( (ans != EOF) && !strchr("yYnN", ans) );
參見strchr
。 我增加了對大寫字母的容忍度。
請注意,您也總是要檢查EOF。 由於不能表示為一個char
,你必須測試seperately和第一 (否則在轉換strchr
可能會產生意想不到的結果。
還要注意,對輸入流進行fflush
(可以在Internet上的某些代碼中找到)是未定義的行為-請勿使用它。 即使某些庫可以容忍它,它們的行為也可能不會達到預期的效果( 未定義的行為暗示)。 沖洗通常是“寫入/發送”數據的語義。 輸入通常是“丟棄的”(並且沒有fdrop
功能。
編輯:添加了內部循環以刪除換行符。 否則,在輸入無效字符后,循環將運行兩次。 假設您必須每行輸入一個字符。
無論您在按Enter鍵之前鍵入什么字母,該行
c = getchar();
仍將換行符留在輸入流中。
如果該字符不是y
和n
,則該調用將在不等待您的情況下執行,並且將換行符分配給c
。 因此,您將看到以下幾行的輸出兩次。
printf("\nWould you like to play again? (y/n):");
和
printf("not y or n");
您需要添加代碼以忽略輸入后的其余行
c = getchar();
添加功能:
void ignoreRestOfLine()
{
int c;
while ( (c = getchar()) != EOF && c != '\n');
}
並將其稱為:
c = getchar();
ignoreRestOfLine();
問題是當您在內存中已經有答案的情況下在do中再次進入程序時。 getchar()
添加一個\\ n,這就是事實。 為了避免這種情況,您可以將ans設置為字符(字符),這意味着它將讀取ascii表; (y = 121,n = 110)。 Char在收到輸入后不會放置\\ n(新行),以確保發生這種情況,您必須在%c之前留一個空格,例如scanf(" %c", &ans);
這意味着ans正在接收一個int。
#include<stdio.h>
#include<stdlib.h>
int main(void){
char ans;
int i = 1;
do
{
printf("\nWould you like to play again? (y/n):");
scanf(" %c", &ans);
if (ans == 121){
printf("yyyyyyyyyyy");
i = i - 1;
}
else if ( ans == 110){
printf("nnnnnnnnnnn");
i = i - 1;
}
else{
printf("not y or n");
}
}
while(i);
}
另一個解決方案:
char c = 'x'; // Initialize to a character other than input
while( c != 'y' || c != 'n') { // You can also use strchr as @Olaf mentioned
printf ("\nPlay again (y/n): ");
c = getchar ();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.