在获取之前在 C. Scanf 中输入.问题 [英] Input in C. Scanf before gets. Problem
问题描述
我对 C 很陌生,我在向程序输入数据时遇到了问题.
I'm pretty new to C, and I have a problem with inputing data to the program.
我的代码:
#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
", &a);
gets 只读取 scanf 留下的 ' '.另外,你应该使用 fgets 而不是 get:http://www.cplusplus.com/reference/clibrary/cstdio/fgets/ 以避免可能的缓冲区溢出.
gets only reads the ' ' 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屋!