C - Standard Input Output
Use stdio.h
for console input/output via printf
, scanf
, and related functions.
Learning Objectives
- Use
printf
for formatted output. - Use
scanf
safely for input. - Handle input errors and buffer issues.
Prerequisites
Basic Input/Output
#include <stdio.h>
int main(void) {
int age;
char name[50];
printf("Enter your name: ");
if (scanf("%49s", name) == 1) { // limit to prevent overflow
printf("Enter your age: ");
if (scanf("%d", &age) == 1) {
printf("Hello %s, you are %d years old.\n", name, age);
} else {
printf("Invalid age input.\n");
}
}
}
Other stdio functions
#include <stdio.h>
int main(void) {
char c;
printf("Enter a character: ");
c = getchar(); // reads one character
printf("You entered: ");
putchar(c); // prints one character
putchar('\n');
char line[100];
printf("Enter a line: ");
if (fgets(line, sizeof line, stdin)) {
printf("Line: %s", line); // fgets preserves newline
}
}
Common Pitfalls
- Forgetting to pass the address (
&x
) toscanf
. - Buffer overflow with unbounded
%s
- use%49s
for a 50-char buffer. - Not checking return values of input functions.
Checks for Understanding
- Why do you pass
&x
toscanf
? - How do you safely read a string into a 50-character buffer?
Show answers
scanf
needs the address to modify the variable.- Use
scanf("%49s", buffer)
orfgets(buffer, 50, stdin)
.