C
Summary - I/O
Combine printf, scanf and getchar to write an interactive menu.
Summary - I/O
In this section you learned printf, scanf, getchar, putchar, puts and fputs. Now we'll combine them in an interactive menu.
The menu first offers a choice to the user (printf), reads the input (scanf), reads one more letter (getchar) and prints the result (printf). Using different I/O tools together in one program is common in C.
Exercise Read a name and greet
Write a C program. Declare char name[32]; and int age;. Print a request line with printf. Read the name with scanf("%31s", name); (no & needed because it's an array). Print another request line with printf, read the age with scanf("%d", &age);. Finally greet with printf using %s and %d specifiers. Put #include <stdio.h> at the top.
Show example solution
#include <stdio.h>
int main(void) {
char name[32];
int age;
printf("Name: ");
scanf("%31s", name);
printf("Age: ");
scanf("%d", &age);
printf("Hello %s, you are %d!\n", name, age);
return 0;
}
Exercise Convert a character to uppercase
Write a C program. Declare int c;. Print a request line with printf. Read a character with c = getchar();. If c >= 'a' && c <= 'z' convert to uppercase with c = c - 'a' + 'A';. Print with putchar(c); and putchar('\n');. Put #include <stdio.h> at the top.
Show example solution
#include <stdio.h>
int main(void) {
int c;
printf("Letter: ");
c = getchar();
if (c >= 'a' && c <= 'z') {
c = c - 'a' + 'A';
}
putchar(c);
putchar('\n');
return 0;
}
Test yourself
-
In what order does an interactive menu work?
printf("Choice: ");
scanf("%d", &n);
- Print, then silently end
- Only read input
- Read input, then show the question
- Show the question, read input, print result
Show answer
Show the question, read input, print result — The menu first asks, then reads, then prints.
-
Read the name
char name[32];
printf("Name: ");
scanf("____", name);
Show answer
char name[32];
printf("Name: ");
scanf("%31s", name);
-
Match the I/O functions
- printf
- Formatted output
- scanf
- Formatted input
- getchar
- Reads one char
- puts
- String + line
Next lesson: The if statement