这是对一些给定字符串进行排序的家庭作业。我提示用户输入他们想要使用 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/