I have written the following code:
#include <stdio.h>
#include <stdbool.h>
#define TRUE 1
#define FALSE 0
int main() {
bool bEndApp=FALSE;
char str[100];
int x, y, z;
int nRet;
bEndApp = FALSE;
printf("How many? ");
scanf("%d", &x);
for (int i=0; i<x; i++) {
printf("entry [%d]\nEnter 2 values separated by space. >> ", i);
nRet=scanf("%d %d", &y, &z);
if (nRet==EOF) { break; }
printf("[scanf] captured: [%d] VAL1: %d VAL2: %d\n\n", i, y, z);
}
fflush(stdin);
do {
printf("Enter command:");
if(fgets(str, sizeof str, stdin)!=NULL) {
printf("\n[fgets] captured: %s\n", str);
} else {
bEndApp=TRUE;
}
} while (bEndApp==FALSE);
printf("End\n");
return 0;
}
When running it, the following output is shown
$ ./test
How many? 3
entry [0]
Enter 2 values separated by space. >> 1 1
[scanf] captured: [0] VAL1: 1 VAL2: 1
entry [1]
Enter 2 values separated by space. >> 2 2
[scanf] captured: [1] VAL1: 2 VAL2: 2
entry [2]
Enter 2 values separated by space. >> 3 3
[scanf] captured: [2] VAL1: 3 VAL2: 3
**Enter command:
[fgets] captured:**
Enter command: this is a test
[fgets] captured: this is a test
Enter command: End
I don't get why the following messages appeared before it runs the actual chunk of code. It seems to print the string and then run the fgets to actually get the user input. fflush(stdin) doesn't seem to help as well.
FYI. I am using DCC to compile the code instead of GCC. Thanks!
Enter command: [fgets] captured: