为什么scanf()总是在等待输入

时间:2015-01-17 16:36:23

标签: c scanf

我正在通过一些关于什么不起作用的例子来更新这个。 scanf不断要求输入一些不应该要求的输入。

int n = 0, i = 0, j = 0;
double a[DIM][DIM];

do
{
    printf("Give the dimension n: ");
    scanf("%d", &n);
}while(n < 2 || n > DIM);

printf("n: %d\n", n);

printf("Give matrix A:\n");
for(i = 0; i < n; i++)
{
    printf("Row %d:\n", i+1);
    for(j = 0; j < n; j++)
    {
        printf("\tCol %d: ",j+1);
        scanf("%lf", &a[i][j]);
    }
}
printf("Workin");

输入示例:

Give the dimension n: 2
n: 2
Give matrix A:
Row 1:
    Col 1: 1.0
    Col 2: 2.0
Row 2:
    Col 1: 3.0
    Col 2: 4.0

有关为什么这不起作用的任何想法? 我可能只是傻了,不是吗?

2 个答案:

答案 0 :(得分:1)

scanf()忽略空格,因此请尝试单独使用

void consumeSpaces()
{
    int chr;
    while ((chr = fgetc(stdin)) && (isspace(chr) != 0));
    ungetc(chr, stdin);
}

int main()
{
    int i, j, n;
    double a[DIM][DIM];

    do
    {
        printf("Give the dimension n: ");
        scanf("%d", &n);
    } while (n < 2 || n > DIM);


    printf("n: %d\n", n);
    printf("Give matrix A:\n");

    consumeSpaces();
    for (i = 0; i < n; i++)
    {
        for (j = 0; j < n; j++)
        {
            consumeSpaces();
            scanf("%lf", &a[i][j]);
        }
    }

    for (i = 0; i < n; i++)
    {
        for (j = 0; j < n; j++)
        {
            printf("a[%d][%d] -> %f\n", i, j, a[i][j]);
        }
    }

    return 0;
}

答案 1 :(得分:-1)

我建议您从scanf读取的数据太短或数字格式不正确。如果扫描数据得到坏数据,它将继续读取,直到它获得良好的数据,但这种方式非常令人困惑。通常使用fgets()和sscanf()。

相关问题