C Formatted I/O
Formatted input and output functions in C allow you to control exactly how data is displayed or read. The printf()
and scanf()
functions are the most commonly used formatted I/O functions in C programming.
The printf() Function
The printf()
function is used to display formatted output to the standard output (usually the console/terminal).
Basic Syntax
int printf(const char *format, ...);
- Returns the number of characters printed, or a negative value if an error occurs
format
is a string that may contain text and format specifiers- Format specifiers start with
%
and are replaced by the values of the additional arguments
Common Format Specifiers
Specifier | Description | Example |
---|---|---|
%d | Signed decimal integer | printf("%d", 42); → 42 |
%u | Unsigned decimal integer | printf("%u", 42); → 42 |
%f | Decimal floating point | printf("%f", 3.14159); → 3.141590 |
%e | Scientific notation | printf("%e", 3.14159); → 3.141590e+00 |
%c | Character | printf("%c", 'A'); → A |
%s | String of characters | printf("%s", "Hello"); → Hello |
%x | Hexadecimal (lowercase) | printf("%x", 255); → ff |
%X | Hexadecimal (uppercase) | printf("%X", 255); → FF |
%o | Octal | printf("%o", 8); → 10 |
%p | Pointer address | printf("%p", &num); → 0x7ffee13be8dc |
%% | Percent sign | printf("%%"); → % |
Format Modifiers
You can use modifiers to control width, precision, alignment, and more:
printf("%10d", 42); // Right-aligned, width 10 → " 42"
printf("%-10d", 42); // Left-aligned, width 10 → "42 "
printf("%.3f", 3.14159); // 3 decimal places → "3.142"
printf("%+d", 42); // Show sign → "+42"
printf("%04d", 42); // Zero padding → "0042"
The scanf() Function
The scanf()
function is used to read formatted input from the standard input.
Basic Syntax
int scanf(const char *format, ...);
- Returns the number of input items successfully matched and assigned
format
specifies the expected format of the input- Subsequent arguments must be pointers to variables where the input will be stored
Important Note
When using scanf()
, you need to pass the address of the variable (using &
), except for arrays (like strings) which are already pointers.
Examples
#include <stdio.h>
int main() {
int num;
float decimal;
char letter;
char name[50];
printf("Enter an integer: ");
scanf("%d", &num); // Note the & operator
printf("Enter a decimal number: ");
scanf("%f", &decimal); // Note the & operator
printf("Enter a single character: ");
scanf(" %c", &letter); // Note the space before %c to consume any whitespace
printf("Enter your name: ");
scanf("%s", name); // No & needed for arrays
printf("\nYou entered:\n");
printf("Integer: %d\n", num);
printf("Decimal: %.2f\n", decimal);
printf("Character: %c\n", letter);
printf("Name: %s\n", name);
return 0;
}
Advanced Format Specifications
Width and Precision
Both printf()
and scanf()
support width and precision specifications:
printf("%*d", width, number); // Width specified as a variable
printf("%.*f", precision, number); // Precision specified as a variable
// Limit input to specific width
scanf("%5s", shortString); // Read max 5 characters into shortString
Scanning with Field Width
int a, b;
scanf("%2d%3d", &a, &b); // If input is "12345", a=12, b=345
Common Mistakes and Tips
scanf() Limitations
scanf()
with%s
stops reading at whitespace:
scanf("%s", name); // Input "John Doe" will only store "John"
- To read a line including spaces, use
fgets()
instead:
fgets(name, sizeof(name), stdin);
// Remove trailing newline if necessary
if (name[strlen(name)-1] == '\n')
name[strlen(name)-1] = '\0';
- Always check the return value of
scanf()
:
if (scanf("%d", &num) != 1) {
printf("Invalid input!\n");
// Handle error
}
- Always include a trailing space when using
scanf()
repeatedly:
scanf("%d ", &num); // Note the space after %d
Buffer Issues
After calling scanf()
to read numeric data, if you want to read character data, it's often necessary to clear the input buffer:
int age;
char name[50];
scanf("%d", &age);
// Clear input buffer (consume newline)
while (getchar() != '\n');
printf("Enter name: ");
fgets(name, sizeof(name), stdin);
Summary
printf()
formats and displays data to the standard outputscanf()
reads and parses data from the standard input- Format specifiers (starting with
%
) control how data is displayed or interpreted - Format modifiers allow control of width, precision, alignment, etc.
- Always use the
&
operator withscanf()
except for arrays (strings) - Be aware of buffer issues and limitations when using these functions
With mastery of formatted I/O, you'll have precise control over how your C programs interact with users.
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)