如果用户输入的数字超过数组的最大值,如何发出错误消息?

How to make an error message if the user puts more numbers than the max value of the array?

我想知道如果用户输入的数字超过数组的最大值时如何发出错误消息。 (用户输入的数字应该在同一行)

#include <stdio.h>
#define N 10

int main() {
    int arr[10];
    int i;
    
    printf("Please enter %d numers\n", N);
    
    for (i=0; i<N; ++i) {
        scanf(" %d", &arr[i]);
    }
    
    for (i=0; i<N; ++i) {
        printf("%d ", arr[i]);
    }
    
    return 0;
}

例如,在我编写的代码中,代码只会忽略超过 10 个数字,但我想知道如何进行错误消息处理。 (如果他放的数字比我想要的少,是一样的吗?)

换句话说,我怎么知道用户输入了多少个数字?

使用函数 scanf 的问题是它会忽略空白字符。由于换行符是一个空白字符,这意味着 scanf 将忽略任何换行符。因此,如果你想强制所有输入的数字都在同一行,那么你不应该使用函数 scanf.

为了读取单行输入,我建议您使用函数fgets. After reading one line of input, you can use the function strtol尝试将字符转换为数字。

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

#define N 10

int main( void )
{
    int arr[N];
    char line[500], *p;

    //prompt user for input
    printf( "Please enter %d numbers: ", N );

    //attempt to read one line of input
    if ( fgets( line, sizeof line, stdin ) == NULL )
    {
        fprintf( stderr, "Input error!\n" );
        exit( EXIT_FAILURE );
    }

    //attempt to read 10 numbers
    p = line;
    for ( int i = 0; i < N; i++ )
    {
        char *q;

        arr[i] = strtol( p, &q, 10 );

        if ( q == p )
        {
            printf( "Error converting #%d!\n", i + 1 );
            exit( EXIT_FAILURE );
        }

        p = q;
    }

    //verify that the remainder of the line contains nothing
    //except whitespace characters
    for ( ; *p != '[=10=]'; p++ )
    {
        if ( !isspace( (unsigned char)*p ) )
        {
            printf( "Error: Non-whitespace character found after 10th number!\n" );
            exit( EXIT_FAILURE );
        }
    }

    //print results
    for ( int i = 0; i < N; i++ )
    {
        printf( "%d ", arr[i] );
    }
    
    return 0;
}

此程序具有以下行为:

Please enter 10 numbers: 1 2 3 4 5
Error converting #6!
Please enter 10 numbers: 1 2 3 4 5 6 7 8 9 10 11
Error: Non-whitespace character found after 10th number!
Please enter 10 numbers: 1 2 3 4 5 6 7 8 9 10   
1 2 3 4 5 6 7 8 9 10 

请注意,我上面的代码存在以下问题:

  1. 它不会检查该行是否太长而无法放入输入缓冲区(即超过 500 个字符)。

  2. 它不会检查用户输入的数字是否可以表示为 int(即它是否大于 INT_MAX,在大多数平台上为 2,147,483,647)。

如果你也想解决这些问题,那我建议你看看我在中的函数get_int_from_user