Character & String I/O
Character input is the lowest-level console tool in C. String input adds buffer sizes, terminators, and one famous unsafe function.
In plain English
Reading characters is like sipping soup one spoon at a time. A string is a whole bowl, with a special end marker.
Character I/O
getchar() reads one character and returns EOF when input ends. putchar() writes one character. getch() is a non-standard console function that reads a key without echo on some compilers. The return type matters: getchar returns int so it can represent both an unsigned char and EOF.
int ch;
while ((ch = getchar()) != EOF) {
putchar(ch);
}String I/O and safe buffers
gets() is unsafe because it cannot know the destination size; never use it in new code. fgets(buffer, size, stdin) reads a bounded line and keeps the newline if there is room. puts() writes a string followed by a newline. Always leave room for the null terminator and strip the newline if your program does not want it.
char line[64];
if (fgets(line, sizeof line, stdin) != NULL) {
size_t n = strlen(line);
if (n > 0 && line[n - 1] == '\n') line[n - 1] = '\0';
printf("you typed: %s\n", line);
}Key takeaways
- getchar returns int so it can return EOF.
- putchar writes one character.
- fgets is bounded; gets is unsafe.
- fgets keeps the newline if it fits.
Common pitfalls
- Storing getchar() in a char, which can hide EOF.
- Forgetting that fgets includes the newline.
- Using gets() with user input.
Key focus
- Know the return values of getchar and fgets.
- Expect a question on why gets() is dangerous.
Quick check
1. What does getchar() return at end of input?
2. Which function safely reads a line into a sized buffer?