Reputation: 741
#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.)
Upvotes: 26
Views: 25932
Reputation: 11
Try this: Don't use \n on scanf, it won't ask you twice and sometimes it might show an error
Your code: scanf("%s\n", a);
Try this on scanf: scanf("%s", a);
Upvotes: 0
Reputation: 63
you can use either of these to avoid the mentioned problem :
scanf("%s",a);
or
scanf("\n%s",a);
Upvotes: 0
Reputation: 11
Remove \n
from the scanf format and give an input and it displays the output based on the given output once.
Upvotes: 0
Reputation: 72667
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.
Upvotes: 27
Reputation: 1315
Don't use the escape sequence in scanf stdio function
scanf ("%s", a);
Upvotes: -1
Reputation: 43528
you have to remove the \n
from the string format of the scanf
. It should be
scanf("%s",a);
EDIT: Explanation
the %s
means that the scanf reads the input character till it gets a delimiter which should be a white space like space or tab or new line(\n
) so the first enter is get as a delimiter for the "%s"
and adding the "\n"
to the string format "%s\n"
means that the scanf will wait 2 newlines the first newline is related to the delimiter of the "%s"
and the second newline is related to the\n
of the string format.
Upvotes: 13
Reputation: 67
use gets() or fgets() instead...alternatively use scanf("%[^\n]s",a);
Upvotes: -1