Summary - I/O
- C course
- Beginner
- Lesson 35/116
- 5 min
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.
Practice 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.
Starter code
#include <stdio.h>
int main(void) {
// Declare name and age, read inputs and greet
return 0;
}Sample 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;
}Expected output
Name: Age: Hello Alex, you are 25!
Practice 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.
Starter code
#include <stdio.h>
int main(void) {
// Declare c, read with getchar, convert to uppercase, write with putchar
return 0;
}Sample 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;
}Expected output
Letter: A
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 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 Correct answer
Explanation: The menu first asks, then reads, then prints.
2 Read the name
char name[32];
printf("Name: ");
scanf("____", name);
char name[32];
printf("Name: ");
scanf("%31s", name);
Explanation: %31s reads up to 31 characters into the string.
3 Match the I/O functions
| Term | Meaning |
|---|---|
printf |
Formatted output |
scanf |
Formatted input |
getchar |
Reads one char |
puts |
String + line |