簡體   English   中英

僅對 c 中的整數使用 scanf

[英]Using scanf only for integers in c

我需要讓用戶輸入 0 到 100 之間的數字。問題是當我在 scanf 中輸入字母時,程序崩潰或將其識別為 0。我想避免任何可能導致我的程序崩潰的用戶錯誤。我使用了 getch以前,但我不知道如何用它獲得多個數字。 關於如何解決這個問題的任何幫助都會很好。 謝謝你。

do
    {
        printf("Enter ID: ");
        scanf("%d", &NewWorkder->id);
        TargetList= FillWorker();
        TargetList= SeekList(Head, NewWorker->id);
    }
    while (NewWorker->id<0 || NewWorker->id>100 || (TargetList)!= (NULL) ||NewWorker->id ==0);
    fprintf(filemechanic,"%s %s %d\n", NewWorker->name, NewWorker->surname, NewWorker->id);
    free(TargetList);
    fclose(filemechanic);
}

根本不要使用scanf 也許您可以使用它的返回值來查看是否根本沒有輸入數字,但是如果您不希望像12ab這樣的輸入有效,那么scanf將無濟於事。

這是一個使用fgetsstrtol檢查有效數字的示例:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    char nptr[1024];
    char *errptr;
    long n = 0;
    do
    {
        printf("Enter a base-10 number: ");
        fgets(nptr, sizeof nptr, stdin);
        n = strtol(nptr, &errptr, 10);
    } while ((*errptr != '\n' && *errptr != '\0') || n < 0 || n > 100);
}

運行示例:

Enter a base-10 number: ab
Enter a base-10 number: 12ab
Enter a base-10 number: -1
Enter a base-10 number: 101
Enter a base-10 number: 123
Enter a base-10 number: 50
[end]

如果要查看scanf是否能夠成功匹配 integer,則必須檢查返回值。

換行

scanf("%d", &NewWorkder->id);

至:

if ( scanf("%d", &NewWorkder->id) != 1 )
{
   fprintf( stderr, "Error reading number!\n" );
   exit( EXIT_FAILURE ); 
}

如果要檢查該值是否在所需范圍內,可以添加以下代碼:

if ( newWorker->id < 0 || newWorker->id > 100 ) )
{
   fprintf( stderr, "Input is out of range!\n" );
   exit( EXIT_FAILURE ); 
}

如果您不希望程序在輸入錯誤時退出,但希望它打印錯誤消息並再次提示用戶,則可以改用以下代碼:

bool bad_input;

do
{
    bad_input = false;

    //prompt user for input
    printf("Enter ID: ");

    //call scanf and verify that function was successful
    if ( scanf("%d", &NewWorkder->id) != 1 )
    {
        printf( "Error reading number, try again!\n" );
        bad_input = true;
    }

    //verify that input is in range
    if ( newWorker->id < 0 || newWorker->id > 100 ) )
    {
        printf( "Number must be between 0 and 100, try again!\n" );
        bad_input = true;
    }

    //discard remainder of line
    for ( int c; (c=getchar()) != EOF && c != '\n'; )
        ;

} while ( bad_input );

但是,對於基於行的輸入,我不建議使用scanf ,因為 function 不會從輸入 stream 中提取整行; 它只提取所需的量。 這可能會造成混淆,並可能導致編程錯誤 相反,我建議改用fgetsstrtol 有關此類解決方案,請參見其他答案。 另外,我建議您閱讀本指南:遠離 scanf() 的初學者指南

暫無
暫無

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

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