2016-10-03 15 views
1
char theInput[10]; 
long option; 
int innerLoop = 1; 
char *dunno; 
while(innerLoop == 1){ 
    printf("\nType '1' to get your change, '2' to select another item, or '3' to add more funds: "); 
    fgets(theInput, sizeof theInput, stdin); 
    option = strtol(theInput, &dunno, 10); 
    if(option == 1){ 
    loop = 0; 
    innerLoop = 0; 
    }else if(option == 2){ 
    loop = 1; 
    outerLoop = 1; 
    innerLoop = 0; 
    firstLoop = 0; 
    }else if(option == 3){ 
    loop = 1; 
    innerLoop = 0; 
    outerLoop = 1; 
    firstLoop = 1; 
    }else{ 
    printf("\nInvalid input, please try again.\n"); 
    innerLoop = 1; 
    } 
} 

該代碼的結果是,當第一次運行時,它打印「類型'1'以獲得」部分後面一個換行符後跟「無效的輸入,請重試。」而不需要從命令行輸入任何信息。然後它再次打印第一個printf語句,然後接受輸入並運行。它意味着打印第一條語句,然後等待輸入。在一個while循環中,fgets()通過自身以換行符運行,作爲輸入

以下是終端輸出。

「輸入‘1’讓你的變化,‘2’,選擇其他項目,或‘3’增添更多的資金。 輸入無效,請重試

輸入‘1’,讓您的變化,「2」,選擇其他項目,或「3」,以增加更多的資金:「

+3

您發佈的代碼不會打印您提到的內容(例如「輸入'C'以獲取您的更改」,部分內容)。這很可能是您的代碼中沒有發佈的部分錯誤.. – nos

+0

感謝您的回覆。這是我在發佈時更新代碼的錯誤 - 我將它從C,N和A更改爲1,2,3,因爲我認爲處理整數可能更容易。我已經更新了這篇文章,因此所有內容都與當前在我的電腦上運行一樣。 – Vorkos

+2

早期未發佈的代碼使用了一個輸入函數,它在'stdin'中留下了''\ n''。 – chux

回答

0

可以嘗試刷新標準輸出?

我已經添加的主要方法如果其他人想有一個工作的例子:

#include <stdio.h> 

int main() { 
    int loop = 0; 
    int outerLoop = 0; 
    int firstLoop = 0; 

    char theInput[10]; 
    long option; 
    int innerLoop = 1; 
    char *dunno; 
    while(innerLoop == 1){ 
    printf("\nType '1' to get your change, '2' to select another item, or '3' to add more funds: "); 
    fflush(stdout); 
    fgets(theInput, sizeof theInput, stdin); 
    option = strtol(theInput, &dunno, 10); 
    if(option == 1) { 
     loop = 0; 
     innerLoop = 0; 
    }else if(option == 2){ 
     loop = 1; 
     outerLoop = 1; 
     innerLoop = 0; 
     firstLoop = 0; 
    }else if(option == 3){ 
     loop = 1; 
     innerLoop = 0; 
     outerLoop = 1; 
     firstLoop = 1; 
    }else{ 
     printf("\nInvalid input, please try again.\n"); 
     innerLoop = 1; 
    } 
    } 
} 

適應你的源代碼之前,你可以嘗試在isoltion運行這個例子,看看如果你有預期成績?