putchar() / getchar() / puts() / gets_s()
Functions for single-character and single-line standard I/O. All are defined in <stdio.h> and are well-suited for simpler input/output than printf()/scanf().
Syntax
// Writes a single character to standard output (equivalent to fputc(c, stdout)). // Returns: the written character on success, EOF on error. int putchar(int c); // Reads a single character from standard input (equivalent to fgetc(stdin)). // Returns: the character read as an int, or EOF on end-of-file or error. int getchar(void); // Writes a string to standard output and automatically appends a newline. // Returns: a non-negative value on success, EOF on error. int puts(const char *str); // Reads up to n-1 characters from standard input (safe replacement for gets(), C11 and later). // Returns: str on success, NULL on failure. char *gets_s(char *str, rsize_t n);
Function List
| Function | Direction | Description |
|---|---|---|
| putchar() | Output | Writes a single character to standard output. The character is passed as an int. |
| getchar() | Input | Reads a single character from standard input. Returns an int so it can be distinguished from EOF. |
| puts() | Output | Writes a string to standard output and automatically appends a newline character ('\n'). |
| gets_s() | Input | Reads one line from standard input. You specify a buffer size, making it safe to use (C11 and later). |
Sample Code
#include <stdio.h>
int main(void) {
// Output strings with puts() — a newline is appended automatically.
puts("Hello, World!"); // Outputs "Hello, World!" followed by a newline.
puts("Learning C!"); // Outputs on the next line.
// Output characters one at a time with putchar().
putchar('A'); // Outputs "A".
putchar('B');
putchar('C');
putchar('\n'); // Outputs a newline.
// Read a character with getchar() and check whether it is uppercase or lowercase.
printf("Enter a character: ");
int ch = getchar(); // Waits for input.
if (ch >= 'a' && ch <= 'z') {
printf("Lowercase: %c\n", ch);
} else if (ch >= 'A' && ch <= 'Z') {
printf("Uppercase: %c\n", ch);
} else {
printf("Not a letter: %c\n", ch);
}
return 0;
}
Notes
puts() automatically appends a newline ('\n') at the end of the string. To do the same with printf() you must include '\n' explicitly, so puts() saves you that step. It is not a good fit, however, when you need output without a trailing newline.
Always store the return value of getchar() in an int variable. If you store it in a char, on platforms where char is signed, EOF (-1) can be confused with the value 255, causing an input loop to never terminate correctly.
gets() is a dangerous, deprecated function. It was removed from the C standard in C11 because it provides no way to specify a buffer size, making buffer overflows inevitable. Use gets_s() (C11 and later) or fgets() instead.
For reading from and writing to files, use fgets() / fputs() / fgetc() / fputc().
If you find any errors or copyright issues, please contact us.