C Input/Output Functions - Complete Guide
Master C input/output functions including printf(), scanf(), format specifiers, return values, and practical programming examples for effective C programming.
printf() & scanf()
Complete reference
Format Specifiers
Complete guide
Practical Examples
Real-world usage
Introduction to C Input/Output
Input/Output (I/O) operations are fundamental to any programming language. In C, I/O is performed using functions from the standard library stdio.h (Standard Input/Output). These functions allow programs to communicate with users by reading input and displaying output.
Key Concepts
- Include
#include <stdio.h>for I/O functions printf()- Output function for displaying datascanf()- Input function for reading data- Format specifiers define data type for I/O operations
- Return values indicate success/failure of operations
Common I/O Functions
- printf(): Formatted output to console
- scanf(): Formatted input from console
getchar(): Read single characterputchar(): Write single charactergets() / fgets(): Read string inputputs(): Write string output
Important Note About stdio.h
The stdio.h header file must be included at the beginning of any C program that uses input/output functions. This file contains declarations for all standard I/O functions and is part of the C Standard Library.
The printf() Function - Complete Guide
The printf() function is used to display formatted output to the standard output (usually the console/screen). It's the most commonly used output function in C.
Syntax:
int printf(const char *format, ...);
Parameters:
| Parameter | Description | Example |
|---|---|---|
format |
Format string containing text and format specifiers | "Value: %d" |
... |
Variable number of arguments matching format specifiers | 10, "Hello", 3.14, etc. |
Return Value:
- Returns the number of characters printed (excluding the null character)
- Returns a negative value if an error occurs
printf("Hello");returns 5printf("Number: %d", 42);returns 9 ("Number: 42" has 9 characters)
Common Format Specifiers for printf():
| Specifier | Data Type | Description | Example |
|---|---|---|---|
| %d | int | Signed decimal integer | printf("%d", 42); |
| %i | int | Signed decimal integer (same as %d) | printf("%i", 42); |
| %u | unsigned int | Unsigned decimal integer | printf("%u", 100U); |
| %f | float/double | Decimal floating point (default 6 decimal places) | printf("%f", 3.14159); |
| %c | char | Single character | printf("%c", 'A'); |
| %s | char* (string) | String of characters | printf("%s", "Hello"); |
| %p | void* | Pointer address | printf("%p", &variable); |
| %x | unsigned int | Hexadecimal integer (lowercase) | printf("%x", 255); // ff |
| %X | unsigned int | Hexadecimal integer (uppercase) | printf("%X", 255); // FF |
| %o | unsigned int | Octal integer | printf("%o", 64); // 100 |
| %e | float/double | Scientific notation (lowercase) | printf("%e", 1234.567); |
| %E | float/double | Scientific notation (uppercase) | printf("%E", 1234.567); |
| %g | float/double | Uses %e or %f, whichever is shorter | printf("%g", 1234.567); |
| %G | float/double | Uses %E or %f, whichever is shorter | printf("%G", 1234.567); |
| %% | None | Prints a literal % character | printf("Discount: 10%%"); |
printf() Examples:
#include <stdio.h>
int main() {
int age = 25;
float salary = 45000.50;
char grade = 'A';
char name[] = "John Doe";
// Basic examples
printf("Hello, World!\n");
// Integer output
printf("Age: %d\n", age);
printf("Age in hex: %x\n", age);
// Floating point output
printf("Salary: %f\n", salary);
printf("Salary with 2 decimals: %.2f\n", salary);
// Character output
printf("Grade: %c\n", grade);
// String output
printf("Name: %s\n", name);
// Multiple values
printf("Employee: %s, Age: %d, Salary: $%.2f, Grade: %c\n",
name, age, salary, grade);
// Return value demonstration
int chars_printed = printf("This is a test\n");
printf("Characters printed: %d\n", chars_printed - 1); // -1 for \n
return 0;
}
Hello, World!
Age: 25
Age in hex: 19
Salary: 45000.500000
Salary with 2 decimals: 45000.50
Grade: A
Name: John Doe
Employee: John Doe, Age: 25, Salary: $45000.50, Grade: A
This is a test
Characters printed: 14
The scanf() Function - Complete Guide
The scanf() function is used to read formatted input from the standard input (usually the keyboard). It's the most commonly used input function in C.
Syntax:
int scanf(const char *format, ...);
Parameters:
| Parameter | Description | Important Notes |
|---|---|---|
format |
Format string containing format specifiers | Must match the type of variables being read |
... |
Pointer to variables where input will be stored | Variables must be passed using address-of operator (&) |
Return Value:
- Returns the number of input items successfully matched and assigned
- Returns EOF if end-of-file is reached or an error occurs before any conversion
- Returns 0 if no input items are matched
scanf("%d", &num);returns 1 if successful, 0 if input is not a numberscanf("%d %f", &a, &b);returns 2 if both values are read successfully
Common Format Specifiers for scanf():
| Specifier | Data Type | Description | Example |
|---|---|---|---|
| %d | int* | Signed decimal integer | scanf("%d", &number); |
| %i | int* | Integer (decimal, octal with 0, hex with 0x) | scanf("%i", &number); |
| %u | unsigned int* | Unsigned decimal integer | scanf("%u", &value); |
| %f | float* | Floating point number | scanf("%f", &floatValue); |
| %lf | double* | Double precision floating point | scanf("%lf", &doubleValue); |
| %c | char* | Single character (reads whitespace too) | scanf("%c", &ch); |
| %s | char* | String (stops at whitespace) | scanf("%s", name); |
| %[ ] | char* | Scanset - reads characters matching set | scanf("%[A-Z]", uppercase); |
| %x | unsigned int* | Hexadecimal integer | scanf("%x", &hexValue); |
| %o | unsigned int* | Octal integer | scanf("%o", &octValue); |
scanf() Examples:
#include <stdio.h>
int main() {
int age;
float height;
char initial;
char name[50];
double salary;
// Reading integer input
printf("Enter your age: ");
int result1 = scanf("%d", &age);
printf("Age: %d, scanf returned: %d\n", age, result1);
// Reading float input
printf("Enter your height in meters: ");
int result2 = scanf("%f", &height);
printf("Height: %.2f meters, scanf returned: %d\n", height, result2);
// Reading character input (note: reads whitespace)
printf("Enter your initial: ");
int result3 = scanf(" %c", &initial); // Space before %c ignores whitespace
printf("Initial: %c, scanf returned: %d\n", initial, result3);
// Reading string input (stops at whitespace)
printf("Enter your first name: ");
int result4 = scanf("%s", name);
printf("Name: %s, scanf returned: %d\n", name, result4);
// Reading multiple values at once
printf("Enter age and height (separated by space): ");
int age2;
float height2;
int result5 = scanf("%d %f", &age2, &height2);
printf("Age: %d, Height: %.2f, scanf returned: %d\n", age2, height2, result5);
// Reading double precision
printf("Enter your salary: ");
int result6 = scanf("%lf", &salary);
printf("Salary: %.2lf, scanf returned: %d\n", salary, result6);
// Checking return value for error handling
int number;
printf("Enter a number: ");
if (scanf("%d", &number) == 1) {
printf("Successfully read: %d\n", number);
} else {
printf("Invalid input!\n");
// Clear input buffer
while (getchar() != '\n');
}
return 0;
}
Enter your age: 25
Age: 25, scanf returned: 1
Enter your height in meters: 1.75
Height: 1.75 meters, scanf returned: 1
Enter your initial: J
Initial: J, scanf returned: 1
Enter your first name: John
Name: John, scanf returned: 1
Enter age and height (separated by space): 30 1.80
Age: 30, Height: 1.80, scanf returned: 2
Enter your salary: 50000.75
Salary: 50000.75, scanf returned: 1
Enter a number: abc
Invalid input!
Practical Examples - printf() and scanf() Together
Here are practical examples that demonstrate how printf() and scanf() work together in real programs:
#include <stdio.h>
int main() {
double num1, num2, result;
char operator;
printf("=== SIMPLE CALCULATOR ===\n");
// Get first number
printf("Enter first number: ");
scanf("%lf", &num1);
// Get operator
printf("Enter operator (+, -, *, /): ");
scanf(" %c", &operator); // Space before %c to skip newline
// Get second number
printf("Enter second number: ");
scanf("%lf", &num2);
// Perform calculation based on operator
switch(operator) {
case '+':
result = num1 + num2;
printf("\nResult: %.2lf + %.2lf = %.2lf\n", num1, num2, result);
break;
case '-':
result = num1 - num2;
printf("\nResult: %.2lf - %.2lf = %.2lf\n", num1, num2, result);
break;
case '*':
result = num1 * num2;
printf("\nResult: %.2lf * %.2lf = %.2lf\n", num1, num2, result);
break;
case '/':
if(num2 != 0) {
result = num1 / num2;
printf("\nResult: %.2lf / %.2lf = %.2lf\n", num1, num2, result);
} else {
printf("\nError: Division by zero is not allowed!\n");
}
break;
default:
printf("\nError: Invalid operator!\n");
}
return 0;
}
#include <stdio.h>
int main() {
char name[50];
int rollNo;
float marks[5];
float total = 0, average;
int i;
printf("=== STUDENT INFORMATION SYSTEM ===\n\n");
// Get student details
printf("Enter student name: ");
scanf(" %[^\n]", name); // Reads string with spaces until newline
printf("Enter roll number: ");
scanf("%d", &rollNo);
printf("\nEnter marks for 5 subjects:\n");
for(i = 0; i < 5; i++) {
printf("Subject %d: ", i+1);
scanf("%f", &marks[i]);
total += marks[i];
}
// Calculate average
average = total / 5;
// Display student information
printf("\n\n=== STUDENT REPORT ===\n");
printf("Name: %s\n", name);
printf("Roll Number: %d\n", rollNo);
printf("\nMarks Obtained:\n");
for(i = 0; i < 5; i++) {
printf("Subject %d: %.2f\n", i+1, marks[i]);
}
printf("\nTotal Marks: %.2f/500.00\n", total);
printf("Average Marks: %.2f\n", average);
printf("Percentage: %.2f%%\n", (total/500)*100);
// Grade calculation
printf("\nGrade: ");
float percentage = (total/500)*100;
if(percentage >= 90) printf("A+ (Excellent)");
else if(percentage >= 80) printf("A (Very Good)");
else if(percentage >= 70) printf("B+ (Good)");
else if(percentage >= 60) printf("B (Average)");
else if(percentage >= 50) printf("C (Pass)");
else printf("F (Fail)");
printf("\n");
return 0;
}
#include <stdio.h>
int main() {
float celsius, fahrenheit, kelvin;
int choice;
printf("=== TEMPERATURE CONVERTER ===\n\n");
printf("Choose conversion:\n");
printf("1. Celsius to Fahrenheit\n");
printf("2. Fahrenheit to Celsius\n");
printf("3. Celsius to Kelvin\n");
printf("4. Kelvin to Celsius\n");
printf("\nEnter your choice (1-4): ");
scanf("%d", &choice);
switch(choice) {
case 1:
printf("\nEnter temperature in Celsius: ");
scanf("%f", &celsius);
fahrenheit = (celsius * 9/5) + 32;
printf("\n%.2f°C = %.2f°F\n", celsius, fahrenheit);
break;
case 2:
printf("\nEnter temperature in Fahrenheit: ");
scanf("%f", &fahrenheit);
celsius = (fahrenheit - 32) * 5/9;
printf("\n%.2f°F = %.2f°C\n", fahrenheit, celsius);
break;
case 3:
printf("\nEnter temperature in Celsius: ");
scanf("%f", &celsius);
kelvin = celsius + 273.15;
printf("\n%.2f°C = %.2f K\n", celsius, kelvin);
break;
case 4:
printf("\nEnter temperature in Kelvin: ");
scanf("%f", &kelvin);
celsius = kelvin - 273.15;
printf("\n%.2f K = %.2f°C\n", kelvin, celsius);
break;
default:
printf("\nInvalid choice! Please select 1-4.\n");
}
return 0;
}
Common Mistakes and Best Practices
Best Practices for C I/O:
- Always check the return value of
scanf()to verify successful input - Use field width specifiers with
%sto prevent buffer overflows - Include a space before
%cinscanf()to skip whitespace - Use
%.2for similar to control decimal places in output - Clear the input buffer after failed
scanf()calls:while(getchar() != '\n'); - Always prompt the user before
scanf()so they know what to enter - Use
printf()return value for debugging output issues
Key Takeaways
- Always include
#include <stdio.h>for I/O functions printf()displays formatted output and returns the number of characters printedscanf()reads formatted input and returns the number of successful conversions- Use
&(address-of operator) with variables inscanf()(except arrays) - Format specifiers must match the data type:
%dfor int,%ffor float,%lffor double - Use
" %c"(space before %c) inscanf()to skip whitespace when reading characters - Check
scanf()return value to validate user input - Limit string input with field width:
%9sfor 9 characters maximum - Control floating point precision:
%.2ffor 2 decimal places - Clear input buffer after errors:
while(getchar() != '\n');