scanf函数输入要求的两倍,而我希望它要求只有一个 [英] scanf asking twice for input while I expect it to ask only one

查看:109
本文介绍了scanf函数输入要求的两倍,而我希望它要求只有一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

char *method1(void)
{
    static char a[4];
    scanf ("%s\n", a);
    return a;
}

int main(void)
{
    char *h = method1();
    printf ("%s\n", h);
    return 0;
}

当我运行上面的code,则提示要求我两次输入(我只在code scanf的使用一次)。这是为什么?

When I run the code above, the prompt is asking me twice for input (I only use scanf for once in the code). Why is that?

推荐答案

从我scanf函数手册页

From my scanf manual page

 White space (such as
 blanks, tabs, or newlines) in the format string match any amount of white
 space, including none, in the input.  Everything else matches only
 itself.

因此​​,用 scanf函数(%S \\ n,A)它会扫描一个字符串,后跟可选的空白。自从第一次换行更多的空白可遵循之后,scanf函数是不是第一个换行符后进行,并期待接下来会发生什么。你会发现,你可以输入任意数量的换行符(或制表符或空格)的和scanf仍然会等待更多。

Thus with scanf ("%s\n", a) it will scan for a string followed by optional white space. Since after the first newline more whitespace may follow, scanf is not done after the first newline and looks what's next. You will notice that you can enter any number of newlines (or tabs or spaces) and scanf will still wait for more.

不过,当你进入第二个字符串,空白的序列分隔,并停止扫描。

However, when you enter the second string, the sequence of whitespace is delimited and scanning stops.

使用 scanf函数(%S,A)不扫描尾随空白。

这篇关于scanf函数输入要求的两倍,而我希望它要求只有一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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