It leaves whatever it cannot read whether through error, end-of-file, or design. If you tell scanf to read an integer and then type "1234abcd\n", "abcd\n" will be left in the stream.
THATS the explanation i've been waiting for !!! i made this example to understand the concept and it went as expected :
Code:
#include <stdio.h>
int main()
{
int x;
char str[BUFSIZ];
scanf("%d", &x);
fgets(str , sizeof(str) , stdin);
printf("%d , %s", x , str);
return 0;
}
when you input '444abc\n' for scanf() it'll leave 'abc\n' in the buffer thus fgets() will read the rest untill it encountres '\n' and terminates ... sweet
BUT i noticed something wierd with another example. See this :
Code:
#include <stdio.h>
int main()
{
char x[BUFSIZ];
char str[BUFSIZ];
scanf("%s", &x);
fgets(str , sizeof(str), stdin);
printf("%s , %s", x , str);
system("PAUSE");
return 0;
}
compile\run it and enter any text. fgets() now will display the same text again !? does it mean that scanf() left the whole string in stdin? it should not leave what it can read , i told it to read a string , so why did it leave the whole string in the stream?? is this an exception or what?
one last question , why doesn't scanf() care if there was a '\n' left in stdin or not? it works in both cases..
i didn't clearly understand the stdout part but thats fine. ill study and research\expirement more about it.
Ill go with your advise and forget about buffers. Now i imagine stdin a stream of bytes going from the keyboard to whatever function uses it. Functions like fgets() takes all the characters from the stream and save them to the memory under their chosen handles , and functions like scanf() might leave some characters in it that might affect other functions using the same stream ... right?
your help is much appreciated