3
votes

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".

2

2 Answers

4
votes

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.

0
votes

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.