C++ Basics · Chapter 7

Input and Output in C++: Console, Files, and Basic Graphics

Learn how to interact with users through the console, read and write files, format output with manipulators, and get an introduction to graphics programming in C++.

By Arj Updated July 2025 14 min read No prior experience needed
What you'll learn
  • How to use cin and cout for console input/output
  • How to format output using manipulators
  • How to read from and write to text files
  • How to handle file errors properly
  • Basic concepts of graphics in C++

1Console input and output

C++ uses cin and cout from the <iostream> library for standard input and output. These are the most basic tools for interacting with the user through the terminal.

How it works:

  • cout displays messages or data to the terminal
  • cin reads input from the user
  • << is the insertion operator (used with cout)
  • >> is the extraction operator (used with cin)

Example:

cpp
#include <iostream>
using namespace std;

int main() {
    int age;
    cout << "Enter your age: ";
    cin >> age;
    cout << "You entered: " << age << endl;
    return 0;
}
Sample runEnter your age: 21 You entered: 21

2Inputting multiple values

You can chain cin to read multiple inputs in a single line. The user can enter values separated by spaces or newlines.

cpp
int a, b;
cin >> a >> b;
cout << "a = " << a << ", b = " << b << endl;
Sample run5 10 a = 5, b = 10
Reading strings with spaces
If you need to read a string that may contain spaces, use getline(cin, name) instead of cin >> name. The extraction operator stops at whitespace.

3Formatting output

C++ provides the <iomanip> library for formatting output. These manipulators give you control over how numbers and text are displayed.

ManipulatorUse
setw(n)Sets width of output
setprecision(n)Controls decimal places
fixedUses fixed-point notation
left, rightAligns text

Example – formatting a decimal number:

cpp
#include <iostream>
#include <iomanip>
using namespace std;

int main() {
    double pi = 3.14159265;
    cout << fixed << setprecision(2) << pi << endl;
    return 0;
}
Output3.14

Example – setting width and alignment:

cpp
cout << setw(10) << "Hello" << endl;
cout << left << setw(10) << "World" << endl;
Output Hello World

4Reading and writing files

To perform file I/O in C++, include the <fstream> library. This gives you:

  • ofstream – for writing to files
  • ifstream – for reading from files
  • fstream – for both reading and writing

Writing to a file

cpp
#include <fstream>
using namespace std;

int main() {
    ofstream outFile("output.txt");
    if (outFile.is_open()) {
        outFile << "Hello, file!" << endl;
        outFile << "This is written using C++." << endl;
        outFile.close();
    }
    return 0;
}

This creates a file named output.txt and writes two lines to it.

Reading from a file

cpp
#include <fstream>
#include <iostream>
#include <string>
using namespace std;

int main() {
    ifstream inFile("output.txt");
    string line;

    if (inFile.is_open()) {
        while (getline(inFile, line)) {
            cout << line << endl;
        }
        inFile.close();
    }
    return 0;
}
OutputHello, file! This is written using C++.

5File check and error handling

Always check whether a file is open before using it. This prevents crashes and helps you debug issues.

cpp
ifstream file("data.txt");
if (!file) {
    cout << "Error opening file." << endl;
    return 1;
}
// Proceed with reading...
Always close your files
While C++ automatically closes files when the program ends, it is good practice to call close() explicitly. This ensures all data is written and resources are freed.

6Simple graphics in C++ (intro)

C++ itself does not have built-in graphics. To create graphical applications, you need to use external libraries like:

  • SFML – Simple and Fast Multimedia Library
  • SDL – Simple DirectMedia Layer
  • graphics.h – Older library used with Turbo C++ (mostly legacy)

Here is a simple program using graphics.h (note: this only works in certain environments like Code::Blocks with proper setup):

cpp
#include <graphics.h>
int main() {
    int gd = DETECT, gm;
    initgraph(&gd, &gm, "");

    circle(200, 200, 100); // draw circle at x=200, y=200, radius=100
    getch();
    closegraph();
    return 0;
}
Graphics requires setup
Graphics programming requires proper library installation and configuration. We will cover this in detail in a dedicated post. For now, focus on the fundamentals of console and file I/O.

7Common mistakes to avoid

1. Forgetting to include headers
Remember to include <fstream> for file I/O and <iomanip> for formatting. Without them, you will get compilation errors.
2. Not checking if a file is open
Always check if (!file) before reading or writing. This prevents crashes when the file does not exist or cannot be accessed.
3. Mixing cin and getline without cin.ignore()
After using cin >>, the newline character stays in the input buffer. When you then use getline(), it will read that newline as an empty line. Use cin.ignore() to clear the buffer.
4. Graphics environment issues
Graphics libraries require specific setup. Do not assume your code will run without installing and configuring the required library and IDE settings.

8Mini exercises

Try these yourself
  1. Ask the user to enter their name and age, and print a message like: Hello Sarah, you are 21 years old.
  2. Create a program that writes 5 numbers to a file, one per line.
  3. Write a program to read numbers from a file and print their sum.
  4. Write a program that asks the user for a number and prints it with 3 decimal places using setprecision.

Hint: For reading numbers from a file, use a loop with file >> num and add to a running total.

9Quiz yourself

Input & Output Quiz
Question 1 of 10
Coming up next
Functions in C++
Learn how to structure your code using reusable functions with parameters, return values, and best practices.
Continue to Chapter 8

Stop wrestling with confusion.

Join thousands of students mastering Computer Science without the academic jargon.

From syntax to systems. We break down the hardest ideas in computer science so you can actually build things.

© 2026 Painless Programming. Built for students.
Scroll to Top