我想编写一个函数来从stdin
读取数据。该函数将被其他函数调用以提示用户输入数据。
void read_data(void) {
// prompt the user by printing a message
// printf("enter data:\n");
int a;
char name[40];
scanf("%d", &a);
// prompt for input again
scanf("%39[^\n]", name);
// do something with the data
}
为了使函数 read_data
正常工作,stdin
流缓冲区中不应有任何无关字符,即它应该为空。该函数不知道上次 scanf
调用中输入的内容,并且输入缓冲区中可能存在整数和字符。
如何确保函数 read_data 正常工作?
最佳答案
void read_data(void) {
// prompt the user by printing a message
// printf("enter data:\n");
int a,c;
char name[40];
scanf("%d", &a);
while((c=getchar()) != '\n');
// prompt for input again
scanf("%39[^\n]", name);
while((c=getchar()) != '\n');
// do something with the data
}
首先使用 scanf
while((c=getchar()) != ' ' && c != '\t' && c != '\n');
因此,如果给定的字符是 '\n',则 getchar 函数获取该字符并检查它是否是新行,如果是新行,如果移动到更远的位置,否则它会到达换行符,以便清除标准输入流缓冲区。
关于c - 丢弃标准输入流缓冲区中的无关字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21019420/