c - 在 scanf 之后,gets() 如何工作? [英] c - how gets() work after scanf?
问题描述
我有两个问题:
- 为什么只有当我在 "%d " -->
scanf("%d ", &num);
中做空格时才有效?
我在 scnaf 和 get 之间尝试了 fflush(stdin) \ _flushall()
但它不起作用,它跳过了 get.
- 当我做空格时,它首先扫描,然后获取,然后打印数字并打印字符串.
<前>无效主(){字符 ch, str[10];整数;printf("请输入您的电话号码:");scanf("%d", #);printf("%d\n",num);获取(字符串);把(字符串);系统(暂停");}
- 为什么只有当我在 "%d " 中做空格 --> scanf("%d ", &num);它有效吗?
scanf("%d", &num);
"%d"
后没有空格,读取一个数字后停止扫描.所以输入 123Enter,'\n'
保持在stdin
用于下一个输入函数,例如现在非标准的 gets()
.gets()
读取单个 '\n'
并返回.通过添加一个空格,scanf("%d ", &num);
消耗了数字后面的空格,直到数字后面输入了非白字符才返回.><块引用>
- 当我做空格时,它首先执行 scanf 然后获取,然后打印数字并打印字符串.
通过添加一个空格,scanf("%d", &num);
直到在数字后面输入非空格(如 'a'
在下面).由于 stdin
通常是行缓冲的,这意味着需要首先输入 2 行.123回车 abc输入.
建议改为使用 fgets()
读取用户输入的行.
char str[10*2];//不需要这么小的缓冲区整数;printf("请输入您的电话号码:");fflush(标准输出);fgets(str, sizeof str, stdin);sscanf(str, "%d", &num);printf("%d\n",num);printf("请输入数据:");fflush(标准输出);fgets(str, sizeof str, stdin);fputs(str, stdout);
更健壮的代码将检查fgets()、sscanf()
的结果并使用strtol()
而不是sscanf()
.
I have two questions:
- why only when i do space in "%d " -->
scanf("%d ", &num);
it works?
I tried fflush(stdin) \ _flushall()
between the scnaf and the gets and it doesn't works, it skips the gets.
- When I do the space, it first does scanf then the gets and after that it print the number and print the string.
void main() { char ch, str[10]; int num; printf("Enter your number : "); scanf("%d ", &num); printf("%d\n",num); gets(str); puts(str); system("pause"); }
- why only when i do space in "%d " --> scanf("%d ", &num); it works?
scanf("%d", &num);
without a space after the "%d"
, stops scanning after reading a number. So with input 123Enter, the '\n'
remains in stdin
for the next input function like the now non-standard gets()
. gets()
reads that single '\n'
and returns. By adding a space, scanf("%d ", &num);
consumes the white-space after the number and does not return until non-white-scape is entered after the number.
- When I do the space, it first does scanf then the gets and after that it print the number and print the string.
By adding a space, scanf("%d ", &num);
does not return until non-white-space is entered after the number (as in 'a'
in the following). Since stdin
is usually line buffered, this means input of 2 lines needs to first occur. 123Enter abcEnter.
Recommend to instead use fgets()
to read a line of user input.
char str[10*2]; // no need for such a small buffer
int num;
printf("Enter your number : ");
fflush(stdout);
fgets(str, sizeof str, stdin);
sscanf(str, "%d", &num);
printf("%d\n",num);
printf("Enter data : ");
fflush(stdout);
fgets(str, sizeof str, stdin);
fputs(str, stdout);
More robust code would check the results of fgets(), sscanf()
and use strtol()
rather than sscanf()
.
这篇关于c - 在 scanf 之后,gets() 如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!