Skip to main content

Section 20.6 Reading Strings from Input

The scanf() function can be used to read a string from the user input using the %s format specifier. By default, reading stops when white space (i.e. a space, return, etc.) is encountered. There are many options to modify this behavior so that the reading stops based on different conditions (if interested: Google).
The below example shows how to read a two words (a first name and a last name) from the user input and store them in corresponding strings.

Compile and run the code below in your own C environment.

#include <stdio.h>
#include <string.h>

int main(void) {
   char firstName[50];
   char lastName[50];
   
   printf("Please enter your first and last name: ");
   scanf("%s %s", firstName, lastName);
   printf("Your name is %s %s.", firstName, lastName);
   return 0;
}

Investigate 20.6.

Why is the ampersand character & missing in front of firstName and lastName in the above scanf() statement?
Hint.
Remember, a string is really an array of characters (with the null terminator placed at the end). Do you remember what an array variable really stores?.