Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

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.)

like image 934
joy Avatar asked Apr 01 '13 08:04

joy


1 Answers

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\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.

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

like image 54
Jens Avatar answered Jan 22 '23 09:01

Jens