You can define a function that does that for you:
bool readline(char *line, size_t size, FILE *stream)
{
if (!fgets(line, size, stream))
return false;
size_t npos = strcspn(line, "\n");
if (line[npos] != '\n') {
flush_stdin();
return false;
}
line[npos] = '\0';
return true;
}
line
: the char
buffer that will hold your input.
size
: the size (capacity) of line
.
stream
: the file stream you want to read from.
In case the number of characters read exceeds the capacity of the buffer, one must flush the input buffer:
int flush_stdin(void)
{
int c = 0;
while ((c = getchar()) != EOF && c != '\n');
return c;
}
As for sscanf()
, use it to parse what has been read by fgets()
.
Here is a demo:
int main(void)
{
char input[64], name[64];
printf("Enter your name: ");
readline(name, sizeof(name), stdin);
printf("Enter your height: ");
readline(input, sizeof(input), stdin);
float height = .0;
if (sscanf(input, "%f", &height) != 1) {
printf("Input error\n");
return 1;
}
printf("Enter your age: ");
readline(input, sizeof(input), stdin);
int age = 0;
if (sscanf(input, "%d", &age) != 1) {
printf("Input error\n");
return 1;
}
printf("%s is %d years old and %.2f feet tall.\n", name, age, height);
}
Enter your name: Johnny
Enter your height: 5.6
Enter your age: 18
Johnny is 18 years old and 5.60 feet tall.
Notes:
- Never use
fflush(stdin)
.
- Skipped checking for
readline()
return values for simplicity.