由於user_choice2
被傳遞給isdigit()
我懷疑user_choice
是char
。使用格式說明"%c"
來填充char
,不"%s"
。格式說明符"%s"
將附加一個空終止符,寫入內存不應該是,並在這種情況下破壞堆棧。
然而,如user_choice2
被傳遞給atoi()
店鋪的用戶輸入在char[]
作爲atoi()
需要一個空終止字符串。通過指定的最大字符數,以防止讀經由scanf()
溢出緩衝液:
char user_choice2[2];
scanf("%1s", user_choice2);
然後在隨後的代碼查詢user_choice2[0]
。
簡單:使用scanf("%d", &user_choice);
直接填充int
其中user_choice
是int
。 scanf()
收益可以用來檢查用戶做出成功的任務數量輸入一個有效的int
:
if (scanf("%d", &user_choice) != 1)
{
/* Not a valid int, skip input. */
char ch;
while ((ch = getchar()) != '\n' && ch != EOF);
}
可我知道如何防止用戶鍵入一個INT遵循字符?例如1a
可以使用格式"%n"
來確定處理結束的位置。使用fgets()
和sscanf()
(不scanf()
)檢測到這種無效的輸入。例如:
char buf[32];
if (fgets(buf, 32, stdin))
{
int value, pos;
if (sscanf(buf, "%d%n", &value, &pos) == 1 &&
pos == strlen(buf) - 1) /* -1 to account for new-line */
{
printf("value=%d\n", value);
}
}
user_choice2是如何定義的? – md5