T
Tomás Ó hÉilidhe
I have a fully-portable C program (or at least I think I do). It works
fine on Windows, but malfunctions on Linux. I suspect that there's
something I don't know about the standard input stream that's causing
the problem.
Here's how I wrote the program originally:
#include <stdio.h>
#include <string.h>
void TrimNewLineOffEnd(char *const str)
{
str[strlen(str) - 1] = 0;
}
int main(void)
{
char buf[20];
unsigned age, siblings;
printf("What age are you? ");
scanf("%u",&age);
printf("How many siblings do you have? ");
scanf("%u", &siblings);
printf("What's your name? ");
fgets(buf,15,stdin);
TrimNewLineOffEnd(buf);
printf("\n\nYour name is %s, you're %u years old and you have %u
siblings!\n\n",
buf,age,siblings);
return 0;
}
This original code didn't work as intended on either Windows or Linux.
On both systems, when control reached "fgets", the user wasn't given a
chance to enter their name; instead, fgets returned immediately with
an empty string.
To remedy this problem on Windows, I put in "fflush(stdin)" right
before the call to "fgets". This fixed the problem and the program
worked as intended. This didn't work on Linux however.
What am I doing wrong?
fine on Windows, but malfunctions on Linux. I suspect that there's
something I don't know about the standard input stream that's causing
the problem.
Here's how I wrote the program originally:
#include <stdio.h>
#include <string.h>
void TrimNewLineOffEnd(char *const str)
{
str[strlen(str) - 1] = 0;
}
int main(void)
{
char buf[20];
unsigned age, siblings;
printf("What age are you? ");
scanf("%u",&age);
printf("How many siblings do you have? ");
scanf("%u", &siblings);
printf("What's your name? ");
fgets(buf,15,stdin);
TrimNewLineOffEnd(buf);
printf("\n\nYour name is %s, you're %u years old and you have %u
siblings!\n\n",
buf,age,siblings);
return 0;
}
This original code didn't work as intended on either Windows or Linux.
On both systems, when control reached "fgets", the user wasn't given a
chance to enter their name; instead, fgets returned immediately with
an empty string.
To remedy this problem on Windows, I put in "fflush(stdin)" right
before the call to "fgets". This fixed the problem and the program
worked as intended. This didn't work on Linux however.
What am I doing wrong?