Hi
Since joining, I have received some great help here so it's time to give back a little which may be of some help to other C noobs like me.
Below is some simple code, syntax wise it's fine and compiles with no errors, however when running it, it behaves very strangely:
#include <stdio.h>
#include <stdlib.h>
int main(){
char StringOne[2];
char StringTwo[10];
printf("Hold down a letter key until you get lots of characters on the screen\n");
fgets(StringOne, 2, stdin);
printf("%s\n", StringOne, "\n" );
printf("Do it again\n");
fgets(StringTwo, 10, stdin);
printf("%s\n", StringOne, "\n" );
return 0;
}
Notice anything strange?
Now this one:
#include <stdio.h>
#include <stdlib.h>
int main(){
char StringOne[2];
char StringTwo[10];
printf("Hold down a key until you get lots of characters on the screen\n");
fgets(StringOne, 2, stdin);
fflush(stdin);
printf("%s\n", StringOne, "\n" );
printf("Do it again\n");
fgets(StringTwo, 10, stdin);
fflush(stdin);
printf("%s\n", StringOne, "\n" );
return 0;
}
Now it works perfectly.
I suppose to the seasoned C programmer, it's only natural and obvious to flush stdin after using things like fgets or getc but not to the newbie and it's not something that is often hinted at,
at least not on the sites I looked at.
Anyway, hope it's of some help to others.