簡體   English   中英

用戶C編程的整數輸入

[英]Integer input by user C programming

該程序用於驗證用戶輸入的整數。 如果數據類型不正確或輸入為空,則返回錯誤。 但只有一次。 我想改變這個程序以不斷詢問用戶直到答案是好的。這是一個“一次性”程序,但我希望它可以用一段時間但它是無限的。

    #include <stdio.h>

    int main()
      {
    int num;
    char term;

    if(scanf("%d%c", &num, &term) != 2 || term != '\n')
    {
        printf("failure\n");
    }
    else 
    {
        printf("valid integer followed by enter key\n");
    }

    return 0;
    }

“......它工作正常,但我無法理解。你能解釋一下嗎?”

scanf() 函數是這段代碼的核心。

scanf()返回成功轉換的項目數。 在此示例中,程序嘗試轉換 2 個項目,因此檢查 return is == 2將確認調用成功。 顯然,編碼器的意圖似乎是驗證是否捕獲了數值和換行符。 對於這個簡單的例子,這段代碼就足夠了,但是scanf()能夠處理更多的. 與此同時, 可以說有更好的用戶輸入替代方案

讓我試試:我已經 5 年沒有接觸過C++/C所以請原諒我的語法錯誤。

做時:

#include <stdio.h>

int main()
{
    int num;
    char term;
    
    do{
        user_input = scanf("%d%c", &num, &term)
        //Code for wrong input
     }
    while(user_input != 2 || term != '\n')
    //Code for right input

    return 0;
}

盡管:

#include <stdio.h>
    
int main()
{
    int num;
    char term;
  
    user_input = scanf("%d%c", &num, &term)
    while(user_input != 2 || term != '\n')
    {
        //Code for wrong input
        user_input = scanf("%d%c", &num, &term)  //In while loop you've to take input again
    }
    //Code for right input
    return 0;
}

暫無
暫無

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

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