如何从一行接受一定数量的输入

时间:2018-04-12 04:36:25

标签: c arrays for-loop

我试图将一些整数输入到二维数组中。我在for循环中使用for循环来遍历数组。我面临的一个问题是,假设2d数组是v [3] [3],当用户在y = 0时输入一行中的4位数时,我想发出错误。我尝试使用计数器来查看用户是否输入了超过所需数量的数据,但我只是转到第二行数组并将第四个整数输入到v [0] [1]。谢谢。

这就是我所尝试的,“if(x == i)”的逻辑是错误的,我不知道如何解决这个问题。

int main(void) {

    // TODO


    int x = -1;
    int y = -1;
    scanf("%d %d", &x, &y);

    if (x <= 0 || y <= 0) {
        printf("Cannot decode\n");
        return 1;
    }

    int v[x][y];

    for (int t=0; t < y; t++) {
        for(int i=0; i < x; i++) {
            // printf("i = %d\nt = %d\n", i, t);

            if (x == i) {
            printf("Cannot decode\n");
            return 1;
            }

            scanf("%d", &v[i][t]);

            // printf("%d-%d\n", i, t);

        }
    }
}

当我尝试使用fgets时,我不断收到错误:

nonogram.c:39:11: error: incompatible integer to pointer conversion 
passing 'char' to parameter of type 'char *'; take the address with & 
[-Werror,-Wint-conversion]
fgets(temp, x, stdin);
^~~~
&
/usr/include/stdio.h:564:38: note: passing argument to parameter '__s' 
here
extern char *fgets (char *__restrict __s, int __n, FILE 
*__restrict__stream)
^
1 error generated.

这就是我做的

        for (int t=0; t < y; t++) {
            for(int i=0; i < x; i++) {

                fgets(temp, x, stdin);
                v[i][t] = atoi(temp);

            }
        }

1 个答案:

答案 0 :(得分:0)

如果我没错,你想根据你的单词给所有y = 0索引提供错误

  

当用户在y = 0时输入一行中的4位数时,我想   发出错误

在所有y=0索引的循环中给出错误,即v[][0],你必须像这样编写if语句:

if(i==0){
print("");
return 1;
}
else{
scanf();
}

绝对x永远不会等于i,因为在你的例子中你说它是3并且在你的代码中你说如果3 == 0然后产生你的错误信息,它将永远不会执行。它总是会跳过你的if语句,因为它每次都会变为false并执行scanf()语句。

注意*如果您不想在iff语句中放置常量,那么您可以使用变量并将其声明为常量。