Skip to main content

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

c
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

SpecifierDescriptionExample
%dSigned decimal integerprintf("%d", 42);42
%uUnsigned decimal integerprintf("%u", 42);42
%fDecimal floating pointprintf("%f", 3.14159);3.141590
%eScientific notationprintf("%e", 3.14159);3.141590e+00
%cCharacterprintf("%c", 'A');A
%sString of charactersprintf("%s", "Hello");Hello
%xHexadecimal (lowercase)printf("%x", 255);ff
%XHexadecimal (uppercase)printf("%X", 255);FF
%oOctalprintf("%o", 8);10
%pPointer addressprintf("%p", &num);0x7ffee13be8dc
%%Percent signprintf("%%");%

Format Modifiers

You can use modifiers to control width, precision, alignment, and more:

c
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

c
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

c
#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:

c
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

c
int a, b;
scanf("%2d%3d", &a, &b); // If input is "12345", a=12, b=345

Common Mistakes and Tips

scanf() Limitations

  1. scanf() with %s stops reading at whitespace:
c
scanf("%s", name);  // Input "John Doe" will only store "John"
  1. To read a line including spaces, use fgets() instead:
c
fgets(name, sizeof(name), stdin);
// Remove trailing newline if necessary
if (name[strlen(name)-1] == '\n')
name[strlen(name)-1] = '\0';
  1. Always check the return value of scanf():
c
if (scanf("%d", &num) != 1) {
printf("Invalid input!\n");
// Handle error
}
  1. Always include a trailing space when using scanf() repeatedly:
c
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:

c
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 output
  • scanf() 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 with scanf() 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! :)