簡體   English   中英

在C中使用scanf()從stdin讀取輸入

[英]Reading input from stdin using scanf() in C

假設輸入為:

6 4
0 1 2 2 1 0
1 0 0 0 0 1
1 0 0 0 0 1
0 1 1 1 1 0

6和4分別是寬度和高度。 我使用的是:

scanf("%d %d", &width, &height);

然后,使用for循環將其余的輸入放入2D數組(board [height] [width])中。 問題在於驗證寬度和高度。

當我輸入

6 4
0 1 2 2 1 0
1 0 0 0 0 1
1 0 0 0 0 
0 1 1 1 1 0

錯過了一個輸入,但等待直到再輸入一個數字。 如果輸入的內容不足或過多,該如何處理並使其出錯?

有人可以幫我解決這個問題嗎? 謝謝!!

您可以使用getsstrtokatoi來完成它。

以下是完整的工作代碼。 看到這里工作:

#include <stdio.h>
#include <string.h>

int main(void) {
    int w, h, i, j;
    char buffer[100];
    scanf("%d %d", &w, &h);
    int num[w][h];
    gets(buffer);
    for(i=0; i<h; i++)
    {
        gets(buffer);
        char *token = strtok(buffer, " ");
        for(j =w; j && token; j--)
        {
            num[i][w-j] = atoi(token);
            token = strtok(NULL, " ");
        }
        if(j)
        {
            //Do what you wish to do on error
            printf("\nError!!! %d inputs are missing\n", j);
        }
    }
    for(int i=0; i<h; i++)
    {
        for(int j =0; j<w; j++)
            printf("%d ", num[i][j]);
        printf("\n");
    }
    return 0;
}

暫無
暫無

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

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