在C中使用scanf()从stdin读取输入 [英] Reading input from stdin using scanf() in C

查看:325
本文介绍了在C中使用scanf()从stdin读取输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设输入为:

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分别是宽度和高度. 我用的是:

6 and 4 are width and height respectively. What I used is:

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

然后,我使用for循环将其余的输入放入2D数组(board [height] [width])中. 问题在于验证宽度和高度.

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.

当我输入

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!!

推荐答案

您可以使用getsstrtokatoi来完成它.

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

这篇关于在C中使用scanf()从stdin读取输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆