Title: strange c problem
Description: scanf won't work?
sofaking - January 2, 2007 06:32 AM (GMT)
I was brushing up on various C-specific things lately when I came across a strange problem:
| CODE |
#include <stdio.h>
int main() { int number; int loop = 0; char c; while (loop == 0) { printf("Enter a number: "); scanf("%i", &number); printf("You entered: %i\n", number); printf("Enter another number? (y/n): "); scanf("%c", &c); if (c != 'y') loop++; } return 0; } |
For some reason, it seems to skip the second scanf in the loop. Doing the same thing with C++ and cout/cin works fine -- why won't it work with printf/scanf?
tubapro12 - January 3, 2007 04:03 AM (GMT)
Try %s in second scanf call.
sofaking - January 3, 2007 04:27 AM (GMT)
C-Man - January 3, 2007 09:27 AM (GMT)
it didn't work cause you got a \n left in the buffer after scanning %i
and %s is not a good idea , if you'd type couple more characters then one it'd go boom
maybe not immediatly but probably when you try a return (Can you say stack corruption ?)
tubapro12 - January 6, 2007 02:01 AM (GMT)
TheHawgMaster - January 8, 2007 08:24 AM (GMT)
That or just load up a big buffer, inefficient solutions are good too :D
(Yeah just flush the stream like tubapro said)