Lesson 70 +10 XP

Reading Strings with scanf

Reading Strings with scanf

scanf can also read words and text, but with a few caveats.

Reading a word

char name[20];
printf("What is your name? ");
scanf("%s", name);
printf("Hello %s\n", name);

Notice: no & for a string! The array name is already an address.

The whitespace problem

%s reads only up to the first space. Type "Ada Lovelace" and only "Ada" lands in the variable.

Reading a full line with fgets

For whole lines including spaces, use fgets:

fgets(name, sizeof(name), stdin);

fgets reads a whole line (up to the buffer size), spaces included.

The stdin source

stdin means "standard input", i.e., the keyboard.

TL;DR

  • scanf("%s", name) reads one word; no & needed for arrays.
  • %s stops at whitespace.
  • fgets(buf, size, stdin) reads a whole line.
  • Buffers need enough room for the text.