Skip to main content

C Input Output

Input and output operations are fundamental to any programming language. They allow us to interact with the user and present our program's results. In C, the standard library provides several functions for handling input and output operations through the stdio.h header.

Including the Standard I/O Header

To perform I/O operations in C, you need to include the standard input-output header file:

c
#include <stdio.h>

This header file contains declarations for functions like printf(), scanf(), getchar(), putchar(), and many others that we'll explore in this guide.

Standard Streams in C

C programs have three standard streams predefined when a program starts execution:

  1. stdin (Standard Input): Default input source, typically the keyboard
  2. stdout (Standard Output): Default output destination, typically the console/screen
  3. stderr (Standard Error): Used for error messages, typically displayed on the screen

Basic Output Functions

The printf() Function

The most commonly used function for output in C is printf() (print formatted). It sends formatted output to the standard output (stdout).

Basic syntax:

c
printf("format_string", argument1, argument2, ...);

Example:

c
printf("Hello, World!\n");

The \n is a newline character that moves the cursor to the next line after printing.

The putchar() Function

The putchar() function outputs a single character to the standard output.

Syntax:

c
putchar(character);

Example:

c
putchar('A');  // Outputs: A

The puts() Function

The puts() function outputs a string followed by a newline character to the standard output.

Syntax:

c
puts(string);

Example:

c
puts("Hello, World!");  // Outputs: Hello, World! (with a newline)

Basic Input Functions

The scanf() Function

The scanf() function reads formatted input from the standard input.

Basic syntax:

c
scanf("format_string", &variable1, &variable2, ...);

Example:

c
int age;
printf("Enter your age: ");
scanf("%d", &age);
printf("You entered: %d\n", age);

Note: The & operator is used to pass the address (memory location) of the variable where the input will be stored.

The getchar() Function

The getchar() function reads a single character from the standard input.

Syntax:

c
variable = getchar();

Example:

c
char ch;
printf("Enter a character: ");
ch = getchar();
printf("You entered: %c\n", ch);

The gets() Function

caution

The gets() function is considered unsafe and has been removed from the C standard library in newer versions due to potential buffer overflow issues. Use fgets() instead.

The fgets() function is a safer alternative to gets() for reading strings:

c
char name[50];
printf("Enter your name: ");
fgets(name, 50, stdin);
printf("Hello, %s", name);

A Complete I/O Example

Let's combine what we've learned to create a simple program that interacts with the user:

c
#include <stdio.h>

int main() {
char name[50];
int age;

// Output prompts and receive input
printf("Enter your name: ");
fgets(name, 50, stdin);

printf("Enter your age: ");
scanf("%d", &age);

// Display the information
printf("\n--- User Information ---\n");
printf("Name: %s", name); // No need for \n as fgets preserves the newline
printf("Age: %d years\n", age);

return 0;
}

Common Issues with I/O Functions

Input Buffer Issues

When mixing different input functions (like scanf() and fgets()), you might encounter issues with the input buffer. For example, after using scanf() to read a number, the newline character remains in the buffer, which can affect subsequent fgets() calls.

To fix this, you can clear the input buffer:

c
int age;
char name[50];

printf("Enter your age: ");
scanf("%d", &age);

// Clear the input buffer
while (getchar() != '\n');

printf("Enter your name: ");
fgets(name, 50, stdin);

Format Specifiers

Ensure you use the correct format specifiers with scanf() and printf() to avoid unexpected behavior:

Format SpecifierData Type
%dInteger
%fFloat
%lfDouble
%cCharacter
%sString
%xHexadecimal
%pPointer

Summary

Basic I/O in C revolves around these key functions:

  • Output: printf(), putchar(), puts()
  • Input: scanf(), getchar(), fgets()

In the next section, we'll dive deeper into formatted I/O with printf() and scanf() to handle more complex input and output patterns.

Practice Exercises

  1. Write a program that asks the user for their first name and last name separately, then greets them using their full name.

  2. Create a program that calculates the area of a rectangle by taking the length and width as input.

  3. Write a program that reads a character and displays its ASCII value.

  4. Implement a simple calculator that takes two numbers and an operator (+, -, *, /) as input, then performs the calculation.



If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)