I/O Operations Console I/O
File I/O Formatting

C++ Input/Output: Complete Guide to cin, cout, and Streams

Master C++ Input/Output operations with short focused examples. Learn console I/O with cin and cout, file operations, stream formatting, and best practices for efficient I/O handling.

Input (cin)

Reading user input

Output (cout)

Displaying results

File I/O

Reading/writing files

Formatting

Custom output formats

C++ Tutorial · Input & Output

Programs communicate through streams. The iostream library provides type-safe input and output—essential for debugging, CLIs, and logging before you tackle files and networking.

What you will learn

  • Use cin, cout, and cerr for console I/O
  • Format output with manipulators (setw, precision, hex)
  • Handle basic input validation patterns
  • Understand stream state and error bits
  • Bridge to file streams in later lessons

Why this topic matters

I/O appears in every assignment and interview coding round. Clean output formatting also improves user-facing tools you build.

Key terms & indexing

C++ cin cout C++ iostream C++ input output C++ formatting

C++ I/O Streams Overview

C++ uses streams for Input/Output operations. Streams are sequences of bytes that flow between your program and input/output devices (keyboard, screen, files). The iostream library provides the foundation for all I/O operations in C++.

cin Standard Input

Object of istream class for reading input from keyboard. Uses extraction operator >>.

cout Standard Output

Object of ostream class for writing output to screen. Uses insertion operator <<.

cerr Standard Error

Unbuffered stream for error messages. Output appears immediately without buffering.

clog Buffered Error

Buffered version of cerr for logging. More efficient for frequent error messages.

Key Concepts:
  • Streams: Abstraction for data flow between program and devices
  • Operators: >> for input (extraction), << for output (insertion)
  • Buffering: Temporary storage for efficiency (except cerr)
  • Header: #include <iostream> required for I/O operations

Basic Console Input/Output

1. Simple Input with cin

Simple Examples

1. Read integer
int age;
cout << "Age: ";
cin >> age;
2. Read double
double salary;
cin >> salary;
3. Read string (no spaces)
string name;
cin >> name;
4. Multiple values
int a, b;
cin >> a >> b;
5. Read char
char grade;
cin >> grade;
6. Prompt then read
cout << "Enter n: ";
int n; cin >> n;

2. Simple Output with cout

Simple Examples

1. Hello World
cout << "Hello, World!" << endl;
2. Print variable
int x = 10;
cout << "x = " << x;
3. Chain output
cout << "Sum: " << 5 + 3 << endl;
4. Newline \n
cout << "Line1\nLine2";
5. Tab character
cout << "A\tB\tC";
6. cerr for errors
cerr << "Error: invalid input";
Important Notes:
  • cin skips leading whitespace (spaces, tabs, newlines)
  • cin >> stops reading at whitespace (can't read strings with spaces)
  • endl adds newline and flushes the output buffer
  • \n adds newline without flushing (more efficient)

Advanced Input Techniques

1. Reading Strings with Spaces (getline)

Simple Examples

1. getline basics
string name;
getline(cin, name);
2. cin.ignore() after >>
int age; cin >> age;
cin.ignore();
getline(cin, name);
3. Full name with spaces
string full = "John Doe";
getline(cin, full);
4. Two getline calls
string city, state;
getline(cin, city);
getline(cin, state);
5. Print getline result
string line;
getline(cin, line);
cout << line;
6. Empty line check
string s;
getline(cin, s);
if (s.empty()) cout << "Empty";

2. Input Validation and Error Handling

Simple Examples

1. Check cin success
int n;
if (cin >> n)
    cout << "OK: " << n;
2. cin.clear()
cin.clear(); // reset error flag
3. Discard bad input
cin.ignore(1000, '\n');
4. Range check
int n; cin >> n;
if (n >= 1 && n <= 100)
    cout << "Valid";
5. tolower for y/n
char ch; cin >> ch;
ch = tolower(ch);
6. Retry loop
while (!(cin >> n)) {
    cin.clear();
    cin.ignore(1000, '\n');
}
Common cin Pitfalls:
  • Buffer Issues: Mixing cin >> and getline() without clearing buffer
  • Type Mismatch: Entering wrong data type causes stream error state
  • No Validation: Not checking if input operations succeed
  • Infinite Loops: Invalid input causing infinite loops without cin.clear()

Output Formatting and Manipulators

1. Formatting Numbers

Simple Examples

1. setprecision(2)
cout << fixed << setprecision(2);
cout << 99.9876; // 99.99
2. scientific
cout << scientific << 1234.5;
3. hex output
int n = 255;
cout << hex << n; // ff
4. setw width
cout << setw(10) << 42;
5. left alignment
cout << left << setw(8) << "Name";
6. boolalpha
bool f = true;
cout << boolalpha << f; // true

2. Useful I/O Manipulators

Manipulator Description Example endl Insert newline and flush output buffer cout << "Hello" << endl; setw(n) Set field width for next output cout << setw(10) << num; setprecision(n) Set decimal precision for floating-point cout << setprecision(2) << price; fixed Use fixed-point notation cout << fixed << num; scientific Use scientific notation cout << scientific << num; left / right Set text alignment in field cout << left << setw(10) << text; setfill(c) Set fill character for padding cout << setfill('*') << setw(10) << num; boolalpha / noboolalpha Display booleans as true/false or 1/0 cout << boolalpha << flag;

File Input/Output

1. Basic File Operations

Simple Examples

1. Write to file
ofstream out("data.txt");
out << "Hello" << endl;
out.close();
2. Read line by line
ifstream in("data.txt");
string line;
while (getline(in, line))
    cout << line;
3. Check file open
ifstream f("x.txt");
if (!f) cerr << "Open failed";
4. Append mode
ofstream a("log.txt", ios::app);
a << "New line\n";
5. Write numbers
ofstream f("nums.txt");
f << 42 << " " << 3.14;
6. fstream both ways
fstream fs("data.txt",
    ios::in | ios::out);

2. File Modes and Error Handling

File Mode Description Example
ios::in Open for reading (default for ifstream) ifstream file("data.txt", ios::in);
ios::out Open for writing (default for ofstream) ofstream file("data.txt", ios::out);
ios::app Append to end of file ofstream file("data.txt", ios::app);
ios::ate Open and seek to end of file fstream file("data.txt", ios::ate);
ios::trunc Truncate file if it exists ofstream file("data.txt", ios::trunc);
ios::binary Open in binary mode ifstream file("data.bin", ios::binary);

Practical Examples

1. Student Grade Calculator

Simple Examples

1. Read student name
string name;
getline(cin, name);
2. Sum marks in loop
double total = 0;
for (int i = 0; i < n; i++) {
    double m; cin >> m;
    total += m;
}
3. Average
double avg = total / n;
cout << avg;
4. Letter grade
char g;
if (avg >= 90) g = 'A';
else if (avg >= 80) g = 'B';
5. Formatted report
cout << left << setw(12)
     << "Average:" << avg;
6. Save to file
ofstream f("report.txt", ios::app);
f << name << " " << avg << endl;

Best Practices & Tips

Input Best Practices
  • Always validate user input
  • Use getline() for strings with spaces
  • Clear buffer after cin >> before getline()
  • Check stream state after input operations
  • Provide clear prompts and error messages
Output Best Practices
  • Use \n instead of endl unless flushing is needed
  • Format output for readability
  • Separate data with clear delimiters
  • Use appropriate precision for numbers
  • Consider localization for international users
File I/O Best Practices
  • Always check if files open successfully
  • Close files when done (RAII helps with this)
  • Use appropriate file modes
  • Handle file errors gracefully
  • Consider using binary mode for non-text data

Summary & Quick Reference

Essential Headers
#include <iostream> - Standard I/O
#include <iomanip> - Formatting
#include <fstream> - File I/O
#include <string> - String handling
Performance Tips
  • Use \n instead of endl when possible
  • Avoid unnecessary cout calls in loops
  • Use string concatenation before output
  • Consider buffering for high-volume I/O

Final Tips

Mastering C++ I/O is essential for creating interactive programs. Start with simple cin/cout operations, then progress to file I/O and advanced formatting. Always handle errors gracefully and validate user input. Remember that efficient I/O can significantly impact your program's performance, especially in console applications.

Frequently asked questions

Is cout faster than printf?

iostream can be slower due to formatting and synchronization; printf is C-style. For learning, cout is clearer and type-safe.

How do I print a newline in C++?

Use std::endl or '\n'. endl also flushes the buffer, which can affect performance in tight loops.

Why does my program skip input?

Often mixing cin >> with getline, or leftover newline in the buffer. Clear cin or use getline consistently.