当格式字符串末尾有换行符时,为什么 scanf 要求输入两次? [英] Why does scanf ask twice for input when there's a newline at the end of the format string?

查看:19
本文介绍了当格式字符串末尾有换行符时,为什么 scanf 要求输入两次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

当我运行上面的代码时,提示要求我两次输入(我只在代码中使用了一次 scanf).这是为什么?

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

(我输入'jo';它要求更多输入,所以我再次输入'jo'.然后它只打印了一次'jo'.)

(I entered 'jo'; it asked for more input, so I entered 'jo' again. Then it only printed out 'jo' once.)

推荐答案

来自我的 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 ", a) 它将扫描后跟可选空格的字符串.由于在第一个换行符之后可能会有更多空格,因此在第一个换行符之后不会执行 scanf 并查看接下来的内容.您会注意到您可以输入任意数量的换行符(或制表符或空格),而 scanf 仍会等待更多.

Thus with scanf ("%s ", 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) 不扫描尾随空格.

Use scanf ("%s", a) to not scan trailing whitespace.

这篇关于当格式字符串末尾有换行符时,为什么 scanf 要求输入两次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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