Reputation: 21
I'm capturing some user input and saving it to both a struct and a file.
For each field, I first write a prompt using printf
, and then capture data to the struct using scanf
, and finally write to file using fprintf
.
The program works fine, but only on one computer, one scanf
executes before its corresponding printf
.
Here's the core of the problem:
printf("\n color: ");
scanf("%s",&robot1.color);
fputs(robot1.color, f);
fputs("\n",f);
printf("\n energy: ");
scanf("%d",&robot1.energy);
fprintf(f,"%d",robot1.energy);
fputs("\n",f);
printf("\n height: ");
scanf("%f",&robot1.height);
fprintf(f,"%.2f",robot1.height);
fputs("\n",f);
printf("\n weight: ");
scanf("%f",&robot1.weight);
fprintf(f,"%.2f",robot1.weight);
fputs("\n",f);
I tested it on two Windows PCs using Dev-C++, and on a Mac using GCC. One of the Windows machines is the one causing all this mess.
The correct execution (user input included) is:
color: red
energy: 100
height: 30.5
weight: 500.0
But in the troublesome computer, after I input the energy value, it shows nothing, and to continue I have to input the height value. After that, I see the height and weight prompts, and finish by capturing the weight:
color: red
energy: 100
30.5
height:
weight: 500.0
The file is written correctly in all cases so, why is only one computer having trouble with scanf
and printf
?
The struct definition is:
typedef struct roboto
{
char name[10];
char color[10];
int energy;
float height;
float weight;
}robot;
Upvotes: 1
Views: 1299
Reputation: 72667
Maybe checking the return value from scanf
would give you some clues. Ignoring that value is just asking for trouble.
Upvotes: 0
Reputation: 2017
The standard output is buffered so you cannot be sure when it will be written.
Call fflush(stdout)
to force the output to be written after calling printf
, then you can be sure that the output will be written.
Upvotes: 3
Reputation: 44093
I am guessing its an issue with stdout
not being flushed before the user is being prompted for input. To fix this you could try flushing stdout after each print statement using fflush(stdout);
. For example:
printf("\n color: ");
fflush(stdout);
scanf("%s",&robot1.color);
fputs(robot1.color, f);
fputs("\n",f);
Upvotes: 4