Reading input from stdin using scanf() in C

前端 未结 1 1783
野趣味
野趣味 2020-12-22 09:44

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 i

相关标签:
1条回答
  • 2020-12-22 10:39

    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;
    }
    
    0 讨论(0)
提交回复
热议问题