c - scanf 和 fgets 的问题

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

这是控制台的样子:

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

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

最佳答案

您必须通过将\n 放入 scanf 来告诉 scanf 破坏\n:

scanf("%d\n", &numStrings)

没有它,scanf 将读取剩余的换行符 [从按下回车键时] 作为循环中的第一行

关于c - scanf 和 fgets 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4929338/

相关文章:

c - 在 C 中使用 fputs 写入文件

c - 使用 C 设置二进制数中的位数

c++ - 检查标准输入是否为空

c++ - 在用户输入时捕获输入流

c - 死亡循环,也许是 scanf

c - 从 C 语言的文本文件中读取 IP 地址

c - 将 char 数组的元素传递到另一个位置

c - 当链表增长超过 100 个元素时,链表头的值会默默地改变

java - Python Java 管道 : dev/stdin file not found exception

c - 为什么 scanf ("%d\n%d\n%d\n",&a,&b,&c);接受 4 个输入。它必须接受 3 个输入,但期望并接受 4 个输入