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:
cityhas no&. An array's name already acts as the address of its first element, so it's passed as is. You'll see why in the arrays and pointers modules.%19slimits the read to 19 characters. An array of 20 chars can hold 19 letters plus the invisible end marker C adds after text. Without a limit, a long word would write past the end of the array, which is a serious bug (a buffer overflow) and a classic security hole. Always give%sa width.
%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.