Reading input from stdin using scanf() in C

2019-01-29 07:20发布

问题:

Assuming that the inputs are:

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 and 4 are width and height respectively. What I used is:

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

Then I put the rest of the inputs in the 2D-array (board[height][width]) using for loops. The problem is about validating the width and height.

When I input

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

one input is missed but it waits until one more number is entered. How can I manage this and make it to occur an error if lack of or too many inputs are being put?

Can someone help me out with this problem? Thanks!!

回答1:

You can use gets, strtok and atoi to get it done.

Following is complete working code. See here working:

#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;
}