Reading Input

Reading Input#

We already saw a basic example of reading from the user when we looked at our sec:first_project.

std::cin works like std::cout, except it reads from input. An we use the input stream operator, >> now.

Listing 27 simple_read.cpp#
#include <iostream>

int main() {

    std::cout << "Enter a number: ";

    double x{};
    std::cin >> x;

    std::cout << "You entered " << x << std::endl;

}

Notice that we create the object / variable that we want to store the input in, and then we read from std::cin into that variable.

Caution

Nothing in this example checks if a number was actually entered.

We can look at std::cin.fail() to see if the read failed (it will be 1 if it fails)).

Listing 28 check_read.cpp#
#include <iostream>

int main() {

    std::cout << "Enter a number: ";

    double x{};
    std::cin >> x;

    std::cout << "You entered " << x << std::endl;

    // if std::cin.fail() is 1, then the read failed
    std::cout << "Failed? " << std::cin.fail() << std::endl;
}

Tip

Shortly we will see how to test on the value returned by std::cin.fail().