输入C. scanf函数之前得到。问题 [英] Input in C. Scanf before gets. Problem
问题描述
我是pretty新的C,和我有输入查询数据的程序有问题。
I'm pretty new to C, and I have a problem with inputing data to the program.
我的code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
int a;
char b[20];
printf("Input your ID: ");
scanf("%d", &a);
printf("Input your name: ");
gets(b);
printf("---------");
printf("Name: %s", b);
system("pause");
return 0;
}
它允许对输入的ID,但它只是跳过输入的其余部分。如果我更改顺序是这样的:
It allows to input ID, but it just skips the rest of the input. If I change the order like this:
printf("Input your name: ");
gets(b);
printf("Input your ID: ");
scanf("%d", &a);
这会工作。虽然,我不能改变顺序,我需要它只是原样。有人能帮助我吗?也许我需要使用一些其他功能。谢谢!
It will work. Although, I CANNOT change order and I need it just as-is. Can someone help me ? Maybe I need to use some other functions. Thanks!
推荐答案
尝试:
scanf("%d\n", &a);
仅获取读取的'\\ n'在scanf函数叶此外,你应该使用与fgets没有得到:<一href=\"http://www.cplusplus.com/reference/clibrary/cstdio/fgets/\">http://www.cplusplus.com/reference/clibrary/cstdio/fgets/以避免可能的缓冲区溢出。
gets only reads the '\n' that scanf leaves in. Also, you should use fgets not gets: http://www.cplusplus.com/reference/clibrary/cstdio/fgets/ to avoid possible buffer overflows.
编辑:
如果以上不工作,请尝试:
if the above doesn't work, try:
...
scanf("%d", &a);
getc(stdin);
...
这篇关于输入C. scanf函数之前得到。问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!