scanf和fgets有问题

gde*_*ohn 3 c stdin scanf fgets

这是为家庭作业分配一些给定的字符串.我正在提示用户他们想要排序scanf的字符串数量,根据该数字分配一个数组,然后自己获取字符串fgets.

如果字符串的数量是硬编码的,那么一切正常,但是scanf让用户决定搞砸了.这是代码:

#include <assert.h>
#include <stdio.h>
#include <stdlib.h>

#define LENGTH  20 // Maximum string length.

int main(void)
{
    int index, numStrings = 0;
    char **stringArray;
    printf("Input the number of strings that you'd like to sort: ");
    assert(scanf("%d", &numStrings) == 1);
    stringArray = (char **)malloc(numStrings * sizeof(char *));

    for (index = 0; index < numStrings; index++)
    {
        stringArray[index] = (char *)malloc(LENGTH * sizeof(char));
        assert(stringArray[index] != NULL);
        printf("Input string: ");
        assert(fgets(stringArray[index], LENGTH, stdin) != NULL);
    }

    // Sort strings, free allocated memory.

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

这是控制台的样子:

Input the number of strings that you'd like to sort: 3
Input string: Input string: foo
Input string: bar

它会跳过循环的第一次迭代,从而在数组的开头产生一个空字符串.我的问题是,为什么会这样做,我该如何解决?


这是控制台看到的格式字符串"%d\n"传递给scanf:

Input the number of strings that you'd like to sort: 3
foo
Input string: Input string: bar
Input string: baz

所以,我可以输入所有的字符串,但字符串的第一个提示是错误的.

Foo*_*Bah 6

你必须通过将\n放在scanf中告诉scanf来破坏\n:

scanf("%d\n", &numStrings)
Run Code Online (Sandbox Code Playgroud)

没有它,scanf将读取剩余换行符[从输入按钮被击中时]作为循环中的第一行