Basic Input and Output in C
Input and output operations are fundamental to any programming language. They allow your program to interact with users, read data from external sources, and display results. In this tutorial, you'll learn how to perform basic input and output operations in C.
The Standard I/O Library
C provides a rich set of I/O functions through the Standard I/O Library, which is accessed by including stdio.h
in your programs:
#include <stdio.h> // Required for input/output functions
Console Output in C
The main function for displaying output in C is printf()
, which stands for "print formatted".
The printf() Function
printf()
allows you to display text and variable values with a specific format:
1#include <stdio.h>23int main() {4 // Simple text output5 printf("Hello, World!\n");67 // Displaying variable values8 int age = 25;9 float height = 1.75;10 char grade = 'A';1112 printf("Age: %d years\n", age);13 printf("Height: %.2f meters\n", height);14 printf("Grade: %c\n", grade);1516 // Multiple values in one statement17 printf("Student Information:\nAge: %d\nHeight: %.2f\nGrade: %c\n",18 age, height, grade);1920 return 0;21}2223// Output:24// Hello, World!25// Age: 25 years26// Height: 1.75 meters27// Grade: A28// Student Information:29// Age: 2530// Height: 1.7531// Grade: A
Format Specifiers
Format specifiers tell printf()
how to display different types of data. They start with a percent sign (%) followed by a character that indicates the data type:
Format Specifier | Data Type | Example |
---|---|---|
%d or %i | Integer | printf("%d", 42); |
%f | Float or Double | printf("%f", 3.14); |
%c | Character | printf("%c", 'A'); |
%s | String | printf("%s", "Hello"); |
%x or %X | Hexadecimal | printf("%x", 255); |
%o | Octal | printf("%o", 8); |
%p | Pointer address | printf("%p", &num); |
%% | Percent sign | printf("%%"); |
Formatting Options
You can control the formatting of your output by using additional options between the % and the format character:
1#include <stdio.h>23int main() {4 int num = 42;5 float pi = 3.14159;67 // Width specification8 printf("[%5d]\n", num); // Output: [ 42] (right-aligned in 5 spaces)9 printf("[%-5d]\n", num); // Output: [42 ] (left-aligned in 5 spaces)1011 // Precision for floating-point12 printf("%.2f\n", pi); // Output: 3.14 (2 decimal places)13 printf("%.4f\n", pi); // Output: 3.1416 (4 decimal places)1415 // Both width and precision16 printf("[%8.3f]\n", pi); // Output: [ 3.142] (8 spaces, 3 decimals)1718 // Zero padding19 printf("[%05d]\n", num); // Output: [00042] (padded with zeros)2021 // Showing positive sign22 printf("[%+d]\n", num); // Output: [+42] (explicit positive sign)2324 return 0;25}2627// Output:28// [ 42]29// [42 ]30// 3.1431// 3.141632// [ 3.142]33// [00042]34// [+42]
Other Output Functions
C provides additional functions for simpler output tasks:
1#include <stdio.h>23int main() {4 // putchar() - Outputs a single character5 putchar('A');6 putchar('\n');78 // puts() - Outputs a string followed by a newline9 puts("Hello, World!"); // Note: puts() automatically adds a newline1011 // fprintf() - Prints to a specific stream (like a file)12 fprintf(stdout, "This goes to standard output\n");1314 return 0;15}1617// Output:18// A19// Hello, World!20// This goes to standard output
Console Input in C
The primary function for reading input in C is scanf()
, which stands for "scan formatted".
The scanf() Function
scanf()
reads input according to a specified format and stores it in the provided variables:
1#include <stdio.h>23int main() {4 int age;5 float height;6 char initial;78 // Reading an integer9 printf("Enter your age: ");10 scanf("%d", &age); // Note the & operator (address-of)1112 // Reading a floating-point number13 printf("Enter your height in meters: ");14 scanf("%f", &height);1516 // Reading a character17 printf("Enter your first initial: ");18 scanf(" %c", &initial); // Note the space before %c to skip whitespace1920 // Displaying the input21 printf("\nYou entered:\n");22 printf("Age: %d years\n", age);23 printf("Height: %.2f meters\n", height);24 printf("Initial: %c\n", initial);2526 return 0;27}2829// Example Interaction:30// Enter your age: 2531// Enter your height in meters: 1.7532// Enter your first initial: J33//34// You entered:35// Age: 25 years36// Height: 1.75 meters37// Initial: J
⚠️ Important Note
When using scanf()
, always use the &
(address-of) operator before the variable name, except for strings (which are already addresses). Forgetting this is a common error that can cause program crashes or unexpected behavior.
Reading Strings
Reading strings with scanf()
requires special attention:
1#include <stdio.h>23int main() {4 char name[50]; // Array to store the string (max 49 characters + null terminator)56 printf("Enter your full name: ");7 scanf("%s", name); // No & needed for arrays/strings89 printf("Hello, %s!\n", name);1011 return 0;12}1314// Example Interaction:15// Enter your full name: John Doe16// Hello, John!
Notice the issue: scanf()
with %s
only reads until the first whitespace, which means it only captured "John" in the example above. To read a full line of text including spaces, use fgets()
:
1#include <stdio.h>2#include <string.h> // For string functions like strlen()34int main() {5 char full_name[50];67 printf("Enter your full name: ");89 // Clear input buffer10 fflush(stdin); // Note: This is not standard C, but works on many systems1112 // Read a full line of text13 fgets(full_name, sizeof(full_name), stdin);1415 // Remove the newline character that fgets keeps16 full_name[strcspn(full_name, "\n")] = 0;1718 printf("Hello, %s!\n", full_name);1920 return 0;21}2223// Example Interaction:24// Enter your full name: John Doe25// Hello, John Doe!
Other Input Functions
C provides several other functions for reading input:
1#include <stdio.h>23int main() {4 char c;5 char buffer[100];67 // getchar() - Reads a single character8 printf("Enter a character: ");9 c = getchar();10 printf("You entered: %c\n\n", c);1112 // Clear the input buffer (consume the newline left by getchar)13 while ((getchar()) != '\n');1415 // gets() - Reads a line of text (DEPRECATED - unsafe!)16 // printf("Enter a line of text: ");17 // gets(buffer); // UNSAFE - can cause buffer overflow!1819 // Better alternative: fgets()20 printf("Enter a line of text: ");21 fgets(buffer, sizeof(buffer), stdin);22 printf("You entered: %s", buffer);2324 return 0;25}2627// Example Interaction:28// Enter a character: A29// You entered: A30//31// Enter a line of text: Hello, C programming!32// You entered: Hello, C programming!
⚠️ Security Warning
Never use the gets()
function as it's considered unsafe and has been removed from the C standard. It doesn't perform bounds checking, which can lead to buffer overflows and security vulnerabilities. Always use fgets()
instead.
Formatted Input and Output
Let's put everything together in a more complete example:
1#include <stdio.h>23int main() {4 // User information5 char name[50];6 int age;7 float height;8 char gender;910 // Gather information11 printf("===== User Registration =====\n");1213 printf("Enter your name: ");14 fgets(name, sizeof(name), stdin);15 // Remove newline character16 for (int i = 0; name[i] != '\0'; i++) {17 if (name[i] == '\n') {18 name[i] = '\0';19 break;20 }21 }2223 printf("Enter your age: ");24 scanf("%d", &age);2526 printf("Enter your height in meters: ");27 scanf("%f", &height);2829 // Clear input buffer before reading a character30 while ((getchar()) != '\n');3132 printf("Enter your gender (M/F): ");33 scanf("%c", &gender);3435 // Display information in a formatted way36 printf("\n===== User Information =====\n");37 printf("| %-20s | %s\n", "Name", name);38 printf("| %-20s | %d\n", "Age", age);39 printf("| %-20s | %.2f meters\n", "Height", height);40 printf("| %-20s | %c\n", "Gender", gender);41 printf("============================\n");4243 return 0;44}4546// Example Interaction:47// ===== User Registration =====48// Enter your name: John Smith49// Enter your age: 3050// Enter your height in meters: 1.8551// Enter your gender (M/F): M52//53// ===== User Information =====54// | Name | John Smith55// | Age | 3056// | Height | 1.85 meters57// | Gender | M58// ============================
File Input and Output
Beyond console I/O, C allows you to read from and write to files:
1#include <stdio.h>23int main() {4 FILE *file_ptr;5 char name[50];6 int age;78 // Writing to a file9 file_ptr = fopen("user_data.txt", "w");1011 if (file_ptr == NULL) {12 printf("Error opening file for writing!\n");13 return 1;14 }1516 printf("Enter your name: ");17 fgets(name, sizeof(name), stdin);18 // Remove newline19 for (int i = 0; name[i] != '\0'; i++) {20 if (name[i] == '\n') {21 name[i] = '\0';22 break;23 }24 }2526 printf("Enter your age: ");27 scanf("%d", &age);2829 fprintf(file_ptr, "Name: %s\nAge: %d\n", name, age);30 fclose(file_ptr);3132 printf("\nData has been written to user_data.txt\n");3334 // Reading from the file35 char buffer[100];36 file_ptr = fopen("user_data.txt", "r");3738 if (file_ptr == NULL) {39 printf("Error opening file for reading!\n");40 return 1;41 }4243 printf("\nFile contents:\n");44 while (fgets(buffer, sizeof(buffer), file_ptr) != NULL) {45 printf("%s", buffer);46 }4748 fclose(file_ptr);4950 return 0;51}5253// Example Interaction:54// Enter your name: John Smith55// Enter your age: 3056//57// Data has been written to user_data.txt58//59// File contents:60// Name: John Smith61// Age: 30
🎯 Try it yourself!
Practice input and output operations by creating programs that:
- Ask the user for three integers and display their sum, average, and product
- Create a simple calculator that takes an operation (+, -, *, /) and two numbers as input
- Read student records (name, ID, grades) from the user and save them to a file
Summary
In this tutorial, you've learned:
- How to display output using
printf()
with different format specifiers - How to read input using
scanf()
and handle different data types - Techniques for reading full lines of text with
fgets()
- Basic file I/O operations for reading from and writing to files
Input and output operations are essential for creating interactive programs that can communicate with users and process external data. In the next tutorials, you'll learn about control flow statements that allow your programs to make decisions and repeat tasks.
Related Tutorials
Variables and Data Types in C
Learn about different data types in C and how to use variables.
Continue learningConditional Statements in C
Learn how to make decisions in your C programs using if statements and more.
Continue learning