C/C++ Arena

Step 4 of 5

Characters and words

Reading one character

%c reads exactly one character, and unlike %d it does not skip whitespace first. If the input is 5 x, reading %d then %c gives you the space, not the x. The fix is a space in the format string before %c: " %c" means "skip whitespace, then read one character".

Reading a word

%s skips whitespace, then reads characters until the next whitespace. The characters go into a char array (a row of chars, which is how C stores text):

#include <stdio.h>

int main(void) {
    char city[20];
    int year;
    char grade;
    scanf("%19s %d %c", city, &year, &grade);
    printf("%s, %d, grade %c\n", city, year, grade);
    return 0;
}
Lisbon 2019 A
Lisbon, 2019, grade A

Two things to notice:

%s stops at spaces, so it reads one word, not a whole sentence. Reading whole lines uses fgets, which you'll meet in the files module.

Your turn: the input is a name followed by a team letter, like s1mple T. Print s1mple plays on T.

Previous: Reading doubles Next: Did the read work?