此代碼請求數據的用戶,並且隨後的數:如何防止用戶輸入比最大限制更多的數據?
$ cat read.c
#include<stdio.h>
#include<stdlib.h>
#define MAX 10
int main() {
char* c = (char*) malloc(MAX * sizeof(char));
int num;
printf("Enter data (max: %d chars):\n", MAX);
fgets(c, MAX, stdin);
// how do I discard all that is there on STDIN here?
printf("Enter num:\n");
scanf("%d", &num);
printf("data: %s", c);
printf("num: %d\n", num);
}
$
的問題是,除了,指出字符的最大數目的指示,沒有什麼進入更停止用戶,這是隨後讀入num
爲垃圾:
$ ./read
Enter data (max 10 chars):
lazer
Enter num:
5
data: lazer
num: 5
$ ./read
Enter data (max 10 chars):
lazerprofile
Enter num:
data: lazerprofnum: 134514043
$
有沒有辦法放棄所有這些都是那裏的fgets
電話後STDIN
?
悲傷但真實。修! – spstanley 2010-11-14 15:40:46
這樣比較好。 '-1'刪除 – pmg 2010-11-14 15:50:17
它應該是'fgets(c,MAX + 1,stdin)'而不是'MAX'。和'fgets(n,sizeof(n),stdin)'而不是'sizeof(n) - 1'。閱讀'fgets'的手冊 – user102008 2010-12-22 00:20:30