Hello,
I am having a problem when I use scanf and then gets().
Why do these two functions confilct together when used one after the other? Maybe I do something wrong?
for example:
Hello,
I am having a problem when I use scanf and then gets().
Why do these two functions confilct together when used one after the other? Maybe I do something wrong?
for example:
scanf("%d") tells the program to get the standard input and load what's there as an integer and then leave the rest in the buffer. That means if your input is something like "9\n" then it just grabs the 9 but leaves the \n in the buffer. So when gets() comes along it sees the \n in the buffer and then decides it's done because gets() reads standard input until it sees a \n. One way to handle this is to use gets() to read the line that contains the number into a character array and then use sscanf() to parse that character array. Usual caveats about buffers sizes and error handling with C I/O apply.
If this object does not have an appropriate type, or if the result of the conversion cannot be represented in the object, the behavior is unde?ned.
Yeah, scanf is bad. sscanf or fscanf though is good if you (yourself) write the string in the format you like before parsing it, it's one of my favourite functions. It makes parsing easy.
^What the moderators said above^
AND
One alternative solution to fix this problem is to use fflush to flush out the buffer. This is what my C/C++ professor made us use to learn C. However, this is non-standard; use it at your own discretion.
char A[20],B[20];
int number;
printf("Number: ");
scanf("%d",&number);
fflush (stdin); // flush out buffer
printf("A: ");
gets(A);
printf("B: ");
gets(B);