Progress: 4 of 16 topics25%

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:

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

c
1#include <stdio.h>
2
3int main() {
4 // Simple text output
5 printf("Hello, World!\n");
6
7 // Displaying variable values
8 int age = 25;
9 float height = 1.75;
10 char grade = 'A';
11
12 printf("Age: %d years\n", age);
13 printf("Height: %.2f meters\n", height);
14 printf("Grade: %c\n", grade);
15
16 // Multiple values in one statement
17 printf("Student Information:\nAge: %d\nHeight: %.2f\nGrade: %c\n",
18 age, height, grade);
19
20 return 0;
21}
22
23// Output:
24// Hello, World!
25// Age: 25 years
26// Height: 1.75 meters
27// Grade: A
28// Student Information:
29// Age: 25
30// Height: 1.75
31// 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 SpecifierData TypeExample
%d or %iIntegerprintf("%d", 42);
%fFloat or Doubleprintf("%f", 3.14);
%cCharacterprintf("%c", 'A');
%sStringprintf("%s", "Hello");
%x or %XHexadecimalprintf("%x", 255);
%oOctalprintf("%o", 8);
%pPointer addressprintf("%p", &num);
%%Percent signprintf("%%");

Formatting Options

You can control the formatting of your output by using additional options between the % and the format character:

c
1#include <stdio.h>
2
3int main() {
4 int num = 42;
5 float pi = 3.14159;
6
7 // Width specification
8 printf("[%5d]\n", num); // Output: [ 42] (right-aligned in 5 spaces)
9 printf("[%-5d]\n", num); // Output: [42 ] (left-aligned in 5 spaces)
10
11 // Precision for floating-point
12 printf("%.2f\n", pi); // Output: 3.14 (2 decimal places)
13 printf("%.4f\n", pi); // Output: 3.1416 (4 decimal places)
14
15 // Both width and precision
16 printf("[%8.3f]\n", pi); // Output: [ 3.142] (8 spaces, 3 decimals)
17
18 // Zero padding
19 printf("[%05d]\n", num); // Output: [00042] (padded with zeros)
20
21 // Showing positive sign
22 printf("[%+d]\n", num); // Output: [+42] (explicit positive sign)
23
24 return 0;
25}
26
27// Output:
28// [ 42]
29// [42 ]
30// 3.14
31// 3.1416
32// [ 3.142]
33// [00042]
34// [+42]

Other Output Functions

C provides additional functions for simpler output tasks:

c
1#include <stdio.h>
2
3int main() {
4 // putchar() - Outputs a single character
5 putchar('A');
6 putchar('\n');
7
8 // puts() - Outputs a string followed by a newline
9 puts("Hello, World!"); // Note: puts() automatically adds a newline
10
11 // fprintf() - Prints to a specific stream (like a file)
12 fprintf(stdout, "This goes to standard output\n");
13
14 return 0;
15}
16
17// Output:
18// A
19// 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:

c
1#include <stdio.h>
2
3int main() {
4 int age;
5 float height;
6 char initial;
7
8 // Reading an integer
9 printf("Enter your age: ");
10 scanf("%d", &age); // Note the & operator (address-of)
11
12 // Reading a floating-point number
13 printf("Enter your height in meters: ");
14 scanf("%f", &height);
15
16 // Reading a character
17 printf("Enter your first initial: ");
18 scanf(" %c", &initial); // Note the space before %c to skip whitespace
19
20 // Displaying the input
21 printf("\nYou entered:\n");
22 printf("Age: %d years\n", age);
23 printf("Height: %.2f meters\n", height);
24 printf("Initial: %c\n", initial);
25
26 return 0;
27}
28
29// Example Interaction:
30// Enter your age: 25
31// Enter your height in meters: 1.75
32// Enter your first initial: J
33//
34// You entered:
35// Age: 25 years
36// Height: 1.75 meters
37// 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:

c
1#include <stdio.h>
2
3int main() {
4 char name[50]; // Array to store the string (max 49 characters + null terminator)
5
6 printf("Enter your full name: ");
7 scanf("%s", name); // No & needed for arrays/strings
8
9 printf("Hello, %s!\n", name);
10
11 return 0;
12}
13
14// Example Interaction:
15// Enter your full name: John Doe
16// 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():

c
1#include <stdio.h>
2#include <string.h> // For string functions like strlen()
3
4int main() {
5 char full_name[50];
6
7 printf("Enter your full name: ");
8
9 // Clear input buffer
10 fflush(stdin); // Note: This is not standard C, but works on many systems
11
12 // Read a full line of text
13 fgets(full_name, sizeof(full_name), stdin);
14
15 // Remove the newline character that fgets keeps
16 full_name[strcspn(full_name, "\n")] = 0;
17
18 printf("Hello, %s!\n", full_name);
19
20 return 0;
21}
22
23// Example Interaction:
24// Enter your full name: John Doe
25// Hello, John Doe!

Other Input Functions

C provides several other functions for reading input:

c
1#include <stdio.h>
2
3int main() {
4 char c;
5 char buffer[100];
6
7 // getchar() - Reads a single character
8 printf("Enter a character: ");
9 c = getchar();
10 printf("You entered: %c\n\n", c);
11
12 // Clear the input buffer (consume the newline left by getchar)
13 while ((getchar()) != '\n');
14
15 // gets() - Reads a line of text (DEPRECATED - unsafe!)
16 // printf("Enter a line of text: ");
17 // gets(buffer); // UNSAFE - can cause buffer overflow!
18
19 // Better alternative: fgets()
20 printf("Enter a line of text: ");
21 fgets(buffer, sizeof(buffer), stdin);
22 printf("You entered: %s", buffer);
23
24 return 0;
25}
26
27// Example Interaction:
28// Enter a character: A
29// You entered: A
30//
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:

c
1#include <stdio.h>
2
3int main() {
4 // User information
5 char name[50];
6 int age;
7 float height;
8 char gender;
9
10 // Gather information
11 printf("===== User Registration =====\n");
12
13 printf("Enter your name: ");
14 fgets(name, sizeof(name), stdin);
15 // Remove newline character
16 for (int i = 0; name[i] != '\0'; i++) {
17 if (name[i] == '\n') {
18 name[i] = '\0';
19 break;
20 }
21 }
22
23 printf("Enter your age: ");
24 scanf("%d", &age);
25
26 printf("Enter your height in meters: ");
27 scanf("%f", &height);
28
29 // Clear input buffer before reading a character
30 while ((getchar()) != '\n');
31
32 printf("Enter your gender (M/F): ");
33 scanf("%c", &gender);
34
35 // Display information in a formatted way
36 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");
42
43 return 0;
44}
45
46// Example Interaction:
47// ===== User Registration =====
48// Enter your name: John Smith
49// Enter your age: 30
50// Enter your height in meters: 1.85
51// Enter your gender (M/F): M
52//
53// ===== User Information =====
54// | Name | John Smith
55// | Age | 30
56// | Height | 1.85 meters
57// | Gender | M
58// ============================

File Input and Output

Beyond console I/O, C allows you to read from and write to files:

c
1#include <stdio.h>
2
3int main() {
4 FILE *file_ptr;
5 char name[50];
6 int age;
7
8 // Writing to a file
9 file_ptr = fopen("user_data.txt", "w");
10
11 if (file_ptr == NULL) {
12 printf("Error opening file for writing!\n");
13 return 1;
14 }
15
16 printf("Enter your name: ");
17 fgets(name, sizeof(name), stdin);
18 // Remove newline
19 for (int i = 0; name[i] != '\0'; i++) {
20 if (name[i] == '\n') {
21 name[i] = '\0';
22 break;
23 }
24 }
25
26 printf("Enter your age: ");
27 scanf("%d", &age);
28
29 fprintf(file_ptr, "Name: %s\nAge: %d\n", name, age);
30 fclose(file_ptr);
31
32 printf("\nData has been written to user_data.txt\n");
33
34 // Reading from the file
35 char buffer[100];
36 file_ptr = fopen("user_data.txt", "r");
37
38 if (file_ptr == NULL) {
39 printf("Error opening file for reading!\n");
40 return 1;
41 }
42
43 printf("\nFile contents:\n");
44 while (fgets(buffer, sizeof(buffer), file_ptr) != NULL) {
45 printf("%s", buffer);
46 }
47
48 fclose(file_ptr);
49
50 return 0;
51}
52
53// Example Interaction:
54// Enter your name: John Smith
55// Enter your age: 30
56//
57// Data has been written to user_data.txt
58//
59// File contents:
60// Name: John Smith
61// 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 learning

Conditional Statements in C

Learn how to make decisions in your C programs using if statements and more.

Continue learning

Loops in C

Learn how to create repetitive tasks in C using loops.

Continue learning