Reading whole lines using fgets#
scanf focuses on space separated data:
#include <stdio.h>
#define LINE_SIZE 100
char line[LINE_SIZE];
int main() {
puts("Please enter your full name:");
scanf("%s", line);
printf("Is your name correct?: %s \n", line);
}
$ echo Anastasia Nikolaevna Romana | code-wi/reading_whole_line_scanf.exe
Please enter your full name:
Is your name correct?: Anastasia
We see in the command output that only the first word is read into the variable, but not the rest.
fgets gets a whole line from a file. The file to read keyboard input is stdin. It additionally needs the maximum number of characters to read.
fgets also stores the trailing newline in the end of a line. So we have to get rid of it (compared to scanf).
#include <stdio.h>
#include <string.h>
#define LINE_SIZE 100
char line[LINE_SIZE];
int main() {
puts("Please enter your full name:");
fgets(line, _Countof line, stdin);
line[strcspn(line, "\n")] = '\0';
printf("Is your name correct?: %s \n", line);
}
$ echo Anastasia Nikolaevna Romana | code-wi/reading_whole_line_fgets.exe
Please enter your full name:
Is your name correct?: Anastasia Nikolaevna Romana
Tip
Use fgets for reading a whole line and scanf for parsing word/s from a line.
Activity 19
Would you use scanf or fgets in Spare parts inventory assistant? Why?
Going back to the problem#
Activity 20
Now use what you have learned to implement Spare parts inventory assistant:
arrays
using
forloops on arraysstring comparison
whilefgets