Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
846 views
in Technique[技术] by (71.8m points)

c - Why does scanf ask twice for input when there's a newline at the end of the format string?

#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;
}

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?

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

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...