簡體   English   中英

do while 循環中 If 語句中的 scanf 弄亂了輸入

[英]scanf inside an If statement on a do while loop messes up the inputs

當輸入為負數 integer 時,程序應詢問是否要重置。

當我用負數 integer 測試它時它工作正常。但是當我嘗試正數 integer 時,它不起作用(我必須輸入兩次)。

int main(void) {
    int user_input;
    char check;

    do
    {
        printf("Enter a positive integer: ");
        scanf("%d", &user_input);

        if (user_input < 0)
            printf("Error. Do you want to continue using the program? y/n: ");
            scanf(" %c", &check);

    } while (check == 'y');

  return 0;
} 

您對scanf的第二次調用應該在方括號內,否則它不是 if 語句的一部分。 與 Python 等語言不同,縮進無關緊要。

無論用戶輸入如何,您的代碼始終執行scanf(" %c", &check)

int main(void) {
    int user_input;
    char check;

    do
    {
        printf("Enter a positive integer: ");
        scanf("%d", &user_input);

        if (user_input < 0) {
            printf("Error. Do you want to continue using the program? y/n: ");
            scanf(" %c", &check);
        }

    } while (check == 'y');

  return 0;
} 

以下塊是相同的:

if (something)
    statementA;
    statementB;
if (something)
    statementA;
statementB;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM