MrlittleMonster
MrlittleMonster

Reputation: 13

What does while (!(cin >> x)) mean?

For context i am trying to make a matrix of an array. This function inserts the numbers in the array

int Readnumber(int i, int j) {

    int number;

    cout << "Give number[" << i << "][" << j << "]: ";
    while (!(cin >> number))
    {
        cout << "Give number[" << i << "][" << j << "]: ";

    }

    return number;
}

Now my question is, what does (!(cin >> number)) mean? I can't figure out what it means.

Upvotes: 1

Views: 1901

Answers (3)

user4581301
user4581301

Reputation: 33931

Lets break while (!(cin >> number)) down.

cin >> number tries to read an int from the console and store it in number, then return the stream object (cin). If a number could not be read from the stream, the stream will be placed in a fault state and the fail bit is set..

!(cin >> number) is a test of the stream returned by cin >> number, and thanks to iostream's operator ! the stream state is tested for failure. If the stream is in a fail state, this results in true.

while (!(cin >> number)) will enter the body of the loop if the read fails or has already failed. Normally inside this loop the failure state would be cleared and the offending input would be removed to prevent failing again as soon as the loop tries to read the next input.

A possible correct solution could look like

while (!(cin >> number)) // while read failed
{
    cin.clear(); // clear error.
    std::string junk;
    if (cin >> junk) // read token that cause failure
    {
        cout << "Give number[" << i << "][" << j << "]: ";
    }
    else
    {
        throw std::runtime_error("Cannot read from cin");
    }
}

Upvotes: 2

Ted Lyngmo
Ted Lyngmo

Reputation: 117298

The purpose is to force the user to enter an integer, but this version fails to take care of the fail state or if the stream is closed. A better version:

std::cout << "Give number[" << i << "][" << j << "]: ";
while(!(std::cin >> number)) {         // enter loop scope if "cin >> number" fails
    if(std::cin.eof()) return -1;      // return if the stream was closed
    std::cin.clear();                  // clear the stream state

    // ignore everything until a newline char is found
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

    std::cout << "Give number[" << i << "][" << j << "]: ";
}

Upvotes: 0

Chad
Chad

Reputation: 19032

cin >> number will read the user input into an integer if possible. The operation may fail. while(!(cin >> number)) therefore, if the operation fails, the loop will execute.

That said, because the failure of the operation is not gracefully handled, the loop in this case will execute forever.

Upvotes: 1

Related Questions