I'm having a bit of difficulty understanding some C code my professor has given me. The code is as follows:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char name[1000];
printf( "What's your name? " );
scanf( "%s", name );
printf( "name is %s\n", name );
scanf( "%[^\n]", name ); /* read the entire line (up to but not
including the '\n' at then end) */
getchar(); /* consume the newline from the input */
printf( "name is %s\n", name );
return EXIT_SUCCESS;
}
The user enters a name and has it printed out twice as such:
What's your name? Dan
name is Dan
name is Dan
It confuses me how this works. The prompt is printed with printf, input is read into the buffer with scanf, and the buffer is printed with printf. However, the \n in the second printf should clear the buffer, so from where is the second scanf reading? I would think it would wait for user input (given an empty buffer) but it doesn't, it simply knows the name. How does this work?