#include<stdio.h>
void main(){
char str[100];
char letter;
letter=getchar();
printf("%c",letter);
gets(str);
//Rest of code
}
On execution, the code skips the gets(str) line. But when I replace gets by scanf, it works. Any specific reason why that doesnt work? I am using gcc 4.7.2.
getchar()
leaves a trailing line feed character'\n'
in stdin. When you callgets()
, it reads until it encounters such a line feed character, which it discards. Since the first character it reads is'\n'
, it immediately stops there.The solution is to make a dummy read to discard the line feed character:
Please note that
void main()
is not valid C (unless you are developing a free running embedded system, which seems unlikely in this case). More info here.Please note that the
gets()
function is no longer part of the C language, it was removed with the C11 version of the standard. Usefgets()
instead.as answered above when you read a character from statndard input the enter you hit after this is placed in stdin buffer which was read by
gets()
in your case . that is whygets()
is not waiting for input.you can use
fflush(stdin)
to clear the input buffer after reading the character .The first call to getchar() leaves a newline character in the input buffer. The next call
gets()
considers that newline as end of input and hence doesn't wait for you to input.Consume the newline character using another getchar().
Note:
gets()
is dangerous as its vulnerable against buffer overflow. So use fgets() instead.