CodeMIRAI
0 XP

Input and output

2 min read 5 runnable examples Quiz included

cin ("character input") reads from the keyboard using the extraction operator >>.

C++
#include <iostream>
using namespace std;

int main() {
    char name[30];
    int age;
    cout << "Name and age: ";
    cin >> name >> age;
    cout << "Hi " << name << "! In ten years you'll be " << age + 10 << "." << endl;
    return 0;
}

cin >> x skips spaces and line breaks, then reads one value of the right type, so several values can be read in one statement.

Reading numbers

C++
#include <iostream>
using namespace std;

int main() {
    int quantity;
    double unitPrice;
    cin >> quantity >> unitPrice;
    cout << "Total: " << quantity * unitPrice << endl;
    return 0;
}

Reading a list

C++
#include <iostream>
using namespace std;

int main() {
    int n, x, total = 0;
    cin >> n;
    for (int i = 0; i < n; i++) {
        cin >> x;
        total += x;
    }
    cout << "Sum = " << total << endl;
    return 0;
}

This "read a count, then that many numbers" pattern is the standard input format of competitive programming problems.

Formatting output

The <iomanip> library controls how numbers look:

C++
#include <iostream>
#include <iomanip>
using namespace std;

int main() {
    double pi = 3.14159265;
    cout << pi << endl;
    cout << fixed << setprecision(2) << pi << endl;
    cout << setprecision(4) << pi << endl;
    return 0;
}
  • fixed switches to a fixed number of decimal places,
  • setprecision(n) sets how many,
  • and both stay in effect for later output.

setw(n) sets the width of the next value, which lines up columns:

C++
#include <iostream>
#include <iomanip>
using namespace std;

int main() {
    cout << setw(8) << "Qty" << setw(10) << "Price" << endl;
    cout << setw(8) << 3 << setw(10) << 4.5 << endl;
    cout << setw(8) << 12 << setw(10) << 19.99 << endl;
    return 0;
}
Finished this lesson?Mark it complete to earn +20 XP and move your progress on.