C语言 我如何使这段代码验证用户输入?

dtcbnfnu  于 2023-05-06  发布在  其他
关注(0)|答案(1)|浏览(155)

下面是我的代码片段(假设变量声明为int类型):

printf("number of rows: ");
    scanf("%d", &x);

    printf("number of columns: ");
    scanf("%d", &y;

    int sample_arr[x][y];

 
    printf("\nEnter elements of the array:\n\n");

    for (i = 0; i < x; i++){
        printf("Row %d: ", i+1);
        for (j = 0; j < y; j++){
            scanf("%d", &arr[i][j]);

代码输出:
行数:3列数:5
输入数组的元素:行1:123//在这里打印一个空格但仍然可以接收用户输入
预期输出:行数:3列数:5
第1行:1 2 3请确保您输入的元素与矩阵的列数相对应!
(Asks用户再次)行1:1 2 3 4 5第五排:1 2 3 4 5
我不知道该怎么办。

cnjp1d6j

cnjp1d6j1#

您需要查看 scanf 的结果,它返回成功匹配和分配的输入项的数量(在本例中为整数)。下面是一个完整的例子:

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

void ReadInteger(int *result)
{
    int n = scanf("%d", result);
    if (n != 1) {
        fprintf(stderr, "integer expected\n");
        exit(EXIT_FAILURE);
    }
}

void ReadPositiveInteger(int *result)
{
    ReadInteger(result);
    if (*result <= 0) {
        fprintf(stderr, "positive integer expected\n");
        exit(EXIT_FAILURE);
    }
}

int main(void)
{
    // read array
    int x, y;
    printf("number of rows: ");
    ReadPositiveInteger(&x);
    printf("number of columns: ");
    ReadPositiveInteger(&y);    
    int sample_arr[x][y];
    printf("\nEnter elements of the array:\n\n");
    for (int i = 0; i < x; i++) {
        printf("Row %d: ", i + 1);
        for (int j = 0; j < y; j++) {
            ReadInteger(&sample_arr[i][j]);
        }
    }

    // print array
    printf("\nHere is the array:\n\n");
    for (int i = 0; i < x; i++) {
        for (int j = 0; j < y; j++) {
            printf("%d ", sample_arr[i][j]);
        }
        putchar('\n');
    }

    return 0;
}

输入/输出示例:

number of rows: 2
number of columns: 3

Enter elements of the array:

Row 1: 1 2 3
Row 2: 3 4 5

Here is the array:

1 2 3 
3 4 5

相关问题