Reaversword
Reaversword

Reputation: 167

Why cin inside while doesn't stop to get user input?

I'm starting now with C++, so I imagine this is gonna be a very easy-newbie question.

Well, why the "cin >> x" line inside while doesn't stop the loop to get the user input (if the user inputs a character, in place of a number)?

#include <iostream>
using std::cin;
using std::cout;
using std::endl;

int main()
{
    int x = 0;
    cout << "Please, enter x: ";
    cin >> x;
    while (!cin)
    {
        cout << "Please, it must be a number!\n";
        cin >> x;
    }
    cout << "Thanks!.";
    cin.ignore();
    cin.ignore();
}

I'm barely two days studiying C++, so I'm completely blind about what "cin" really is. I tried with "cin.sync()" and "cin.clear()", but still no luck. And I know it is impossible to do something like "cin=true", or "cout << cin".

Upvotes: 3

Views: 4504

Answers (2)

Vladimir Svyatski
Vladimir Svyatski

Reputation: 490

Well, your program should be corrected slightly

#include <iostream>
using std::cin;
using std::cout;
using std::endl;

int main()
{
    int x = 0;
    cout << "Please, enter x: ";
    cin >> x;
    while (!cin)
    {
        cin.clear();
        cin.ignore(10000, '\n');
        cout << "Please, it must be a number!" << endl;
        cin >> x;
    }
    cout << "Thanks!.";
}

This way it works as expected. More info about it here. In general, you need to clear all the errorneous stuff from cin.

Upvotes: 4

user5367527
user5367527

Reputation:

if user input a character than it will take the ascii value of character so it will not stop. To stop the loop enter 0.

Upvotes: 0

Related Questions