这是一项家庭作业,用于对某些给定的字符串进行排序。我提示用户输入他们想要排序的字符串数量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
因此,我可以输入所有字符串,但第一个字符串提示位于错误的位置。