このコードは、ユーザーにデータとそれに続く番号を要求します。
$ 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
$
通話STDIN
後に残っているものをすべて破棄する方法はありますか?fgets