So, I was trying to understnad strcmp listed on this site.
http://www.cplusplus.com/reference/cstring/strcmp/
What is the purpose for using fflush(stdout) in the example program provided on the above site?
I remove that line, and the program seems to work just fine without it.
I realize that I should probably tell you how I'm compiling it:
Using:
Windows 10 cmd.exe command prompt
Added a path variable to the Cygwin folder that contains g++ and gcc executables
I typically use g++ to compile it, but it seems this program can use either gcc or g++ to compile.
Now, I have changed the 80 in buffer[80] to different numbers
I have also changed the 79 in scanf ("%79s",buffer) to different numbers.
I have discovered that if you put an answer that contains more characters than the number shown originally as %79s then when you press enter, the question is printed more than once. I shortened that to %10s. Then the question repeats itself once for every over 10 characters used in the answer. For example, if I use 11 to 20 characters, it prints the question twice. If I use 41 to 50 characters, it prints the question 5 times.
This behavior happens whether or not I use the fflush or comment that line out.
Likewise, I discovered that there are ways to input characters so that it breaks the program so that even if I put "apple," which is the correct answer, it still doesn't read it. This also seems to happen irrespective of whether I have the fflush line included when compiling.
I have also discovered that so long as the number in buffer[80] remains higher than the number in the %79s, then when you cause the repeat, you can type the correct answer right at the character that will cause the next repeat and you'll get the question repeated, but when it reaches that correct answer repeat, it will return the correct answer prompt and close the program. It also does this irrespective of whether the fflush line is included.
So, I cannot for the life of me figure out what the fflush line is doing. I cannot figure out how or even if it's contributing anything to the program.
I have copy-pasted the example program below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
#include <stdio.h>
#include <string.h>
int main ()
{
char key[] = "apple";
char buffer[80];
do {
printf ("Guess my favorite fruit? ");
fflush (stdout);
scanf ("%79s",buffer);
} while (strcmp (key,buffer) != 0);
puts ("Correct answer!");
return 0;
}
|