Reading whole lines using fgets

Contents

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

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>

#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_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 20

Would you use scanf or fgets in Spare parts inventory assistant? Why?

Activity 21

Now use what you have learned to implement Spare parts inventory assistant:

  • arrays

  • using for loops on arrays

  • string comparison

  • while

  • fgets

Appendix#