getchar does not stop when using scanf
Posted
by
Oz123
on Stack Overflow
See other posts from Stack Overflow
or by Oz123
Published on 2012-09-29T15:11:31Z
Indexed on
2012/09/29
15:37 UTC
Read the original article
Hit count: 315
I am have a difficulty understanding getchar()
. In the following program getchar
works as expected:
#include <stdio.h>
int main()
{
printf("Type Enter to continue...");
getchar();
return 0;
}
However, in the following program, getchar
does not create a delay and the program ends:
#include <stdio.h>
int main()
{
char command[100];
scanf("%s", command );
printf("Type Enter to continue...");
getchar();
return 0;
}
I have the following weired workaround, which works, but I understand why:
#include <stdio.h>
int main()
{
char command[100];
int i;
scanf("%s", command );
printf("Type Enter to continue...");
while ( getchar() != '\n') {
i=0;
}
getchar();
return 0;
}
So my questions are:
1. What is scanf
doing? Why does scanf
do this ?
2. Why is my work around working?
3. What is a good way to emulate the following Python code:
raw_input("Type Enter to continue")
© Stack Overflow or respective owner