Scanf - is the program waiting for another?

In the next program, I expect that after entering a word and pressing the enter key, I should immediately see the message printfed out. However, this does not happen until I enter some other random word. Why is this?

#include <cstdio>
#include <cstdlib>

using namespace std;

char tictac[17];

int main() 
{
    scanf("%s\n", tictac);


    printf("%s\n", tictac);
    return 0;
}
+5
source share
3 answers

tl; dr : with scanf("%s\n", tictac);you ask to read a line, ignore all spaces after it, and then read a new line. The problem is that the first space is ignored, since the first space must be at least one non-empty character between the first Enterand second Enter(therefore, the need for some unnecessary garbage input before the second is Enteraccepted.).


\n scanf.

char x, y;
scanf("%c", &x); 
scanf("%c", &y);
printf("%c %c", x,y); 

, Enter printf. , scanf ( ) y.

scanf("\n%c", &y);  // This is recommended to do if you have a sequence of scanfs (but not on the first one).

( ) \n. y.


,

scanf("%s\n", tictac);

%s scanf , blank character (space, tab or new line), , . , scanf Enter, , . , ( enter.)

, ( char)

scanf("%s", tictac);
scanf("%s", tictac2);

Windows

"% s" , , "% [^\0x20\t\n]", , (\ 0x20), (\ t) (\n).

, scanf \n

scanf("%s\n", tictac);
         ^^

, \n ( ), %s.

+4

\n scanf.

+3

There is a good scanf explanation here . In your case, you must remove \ n from the scanf function.

+1
source

All Articles