是否scanf()的采取的'\\ n'作为输入从剩余previous scanf()的? [英] Does scanf() take '\n' as input leftover from previous scanf()?

查看:144
本文介绍了是否scanf()的采取的'\\ n'作为输入从剩余previous scanf()的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的C code:

In the following C code:

char name[20];
int a;
int b;

for(i=0;i<10;i++)
{
    printf("\nEnter name, a & b: ");
    scanf("%s %d %d",name,&a,&b);
}

确实在的'\\ n'在年底进入 scanf函数读 scanf函数 ()在第1次迭代,为第二次迭代投入?

does scanf read in the '\n' entered at the end of scanf() in 1st iteration, for the 2nd iteration inputs?

推荐答案

scanf函数叶指向输入流中的 \\ n 。在你的情况下,它不会有所作为:每次它叫的时候, scanf函数沿,直到找到下一个非空白字符将移动。所以给它10行名称,A,B 作为像您期望的输入会工作。

scanf leaves the input stream pointing to the \n. In your case it doesn't make a difference: each time it's called, scanf will move along until it finds the next non-whitespace character. So giving it 10 lines of name, a, b as input will work as you expect.

不过考虑这个问题:

scanf("%d", &a);
fgets(str, 20, stdin);

与fgets 读取,直到它找到第一个换行符,所以 STR 只会得到<$ C的值$ C> \\ n 和与fgets 将的的读取输入的下一行。

fgets reads until it finds the first newline character, so str will just get a value of \n, and fgets will not read the next line of input.

这篇关于是否scanf()的采取的'\\ n'作为输入从剩余previous scanf()的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆