C++ Input and Output: cin, cout and std::print

C++ reads and writes data with streams. std::cout is the output stream, std::cin is the input stream. They are in the header <iostream>.

Output with cout

#include <iostream>

int main() {
    int age = 21;
    double marks = 88.5;
    std::cout << "Age: " << age << ", marks: " << marks << '\n';
    std::cout << "Sum: " << 2 + 3 << '\n';
}
Output

Age: 21, marks: 88.5
Sum: 5

Input with cin

#include <iostream>
#include <string>

int main() {
    std::string name;
    int age;
    double marks;

    std::cin >> name >> age >> marks;       // reads one value at a time, split by spaces
    std::cout << name << " is " << age << " years old and has " << marks << " marks\n";
}
Output

Riya is 21 years old and has 88.5 marks

Read a full line with getline

cin >> stops at a space. Use std::getline to read a full sentence.

#include <iostream>
#include <string>

int main() {
    std::string full_name;
    std::getline(std::cin, full_name);
    std::cout << "Hello, " << full_name << "!\n";
}
Output

Hello, Riya Sharma!

The newline problem

After cin >> number the Enter key stays in the input, so a following getline reads an empty line. Clear it with std::cin.ignore(...):

#include <iostream>
#include <limits>
#include <string>

int main() {
    int age;
    std::string name;
    std::cin >> age;
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');   // throw away the rest of the line
    std::getline(std::cin, name);
    std::cout << age << " " << name << '\n';
}
Output

25 Riya Sharma

Check if the input is valid

#include <iostream>

int main() {
    int n;
    if (std::cin >> n) {
        std::cout << "Number: " << n << '\n';
    } else {
        std::cout << "That is not a number\n";
    }
}
Output

That is not a number

Formatting

<iomanip> has old style manipulators. The modern way is std::format (C++20) and std::print (C++23):

#include <iomanip>
#include <iostream>
#include <print>

int main() {
    double pi = 3.14159265;
    std::cout << std::fixed << std::setprecision(2) << pi << '\n';   // old way
    std::println("{:.2f}", pi);                                       // new way
    std::println("{:>8}|{:<8}|{:^8}|", "right", "left", "mid");
    std::println("{:05d} {:x} {:b}", 42, 255, 5);
}
Output

3.14
3.14
right|left | mid |
00042 ff 101

FormatMeaning
{:.2f}2 digits after the point
{:>8}Right align in 8 places
{:<8}Left align
{:05d}Number with zeros, 5 places
{:x}, {:b}Hexadecimal, binary
Note: When the input is not a number, cin goes into a fail state. Check it as above. Next: C++ Variables.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.