這是一個家庭作業分配一些給定的字符串。我提示用戶輸入他們想要排序的字符串數量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
它會跳過循環的第一次迭代,導致在數組的開頭空字符串。我的問題是,爲什麼會這樣做,我該如何解決?
這裏是控制檯看起來與傳遞給scanf
格式字符串"%d\n"
:
Input the number of strings that you'd like to sort: 3 foo Input string: Input string: bar Input string: baz
所以,我可以輸入的所有字符串的,但對於一個字符串的第一個提示是放錯了地方。
請勿對可能合理預期失敗的函數(如讀取用戶輸入的輸入函數)進行`assert()`。這比忽略錯誤要好。它不如處理錯誤理智。 – 2011-02-08 04:08:25
@Jonathan感謝您的建議。 – gdejohn 2011-02-08 04:30:22