这是一个作业任务,需要对给定的字符串进行排序。我要求用户使用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;
}
以下是控制台的样子:
输入您想要排序的字符串数量: 3 输入字符串: foo 输入字符串: bar
它跳过了循环的第一次迭代,导致数组开头为空字符串。我的问题是,为什么会这样,我该如何解决?
当将格式字符串"%d\n"
传递给scanf
时,控制台显示如下:
输入您想要排序的字符串数量: 3 foo 输入字符串: bar 输入字符串: baz
因此,我可以输入所有字符串,但是第一个字符串的提示在错误的位置。
assert()
,比如读取用户输入的输入函数。这比忽略错误要好,但不如合理地处理错误。 - Jonathan Leffler