簡體   English   中英

如何使用scanf獲取用戶在C語言中輸入的數據?

[英]How can I get the data entered by the user in C using scanf?

    //get choice input 
    int n;
    scanf ("%d",&n);
    // print the option that the user entered i.e. you chose option 2
    printf("you chose option %n /n" ,n); 

對不起新手問題; 我以前沒有做過C編碼!

有兩個問題。 第一個%n (令人恐怖地)是一個輸出項; 它會寫一個指向int的指針-並且您沒有為它提供一個指向int的指針,因此您將調用未定義的行為。 %i%d (最通常為%d )用於純(帶符號)整數。

在輸出換行符之前,您也不會看到printf()輸出,否則程序將終止,因為您輸錯了換行符轉義序列(它是\\n ,而不是/n )。 因此,您的代碼

printf("you chose option %n /n" ,n); 

應該修改為:

printf("you chose option %d\n", n);

最后(現在),您還應該驗證scanf()的返回值; 如果它告訴您轉換失敗,則不要嘗試使用n

if (scanf("%d", &n) == 1)
    printf("you chose option %d\n", n);
else
    printf("Oops - failed to read an integer from your input\n");

請注意,如果用戶鍵入“ a”(例如),則重試讀取整數的操作將無效。 您可能需要吞噬其余的輸入行:

else
{
    printf("Oops - failed to read an integer from your input\n";
    int c;
    while ((c = getchar()) != EOF && c != '\n')
        ;
}

現在可以安全地返回並重試。

我用該代碼看到的唯一問題是來自printf的描述符。 應該是%d 對於新行, \\n也不是/n (但這不會引起任何問題)。 所以試試這個:

#include <stdio.h>

void main()
{
       //get choice input 
        int n;
        scanf ("%d",&n);
        // print the option that the user entered i.e. you chose option 2
        printf("you chose option %d \n" ,n); 
}

暫無
暫無

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

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