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

≯℡__Kan透↙ 提交于 2019-12-11 13:34:02

问题


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


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/33168544/why-cin-inside-while-doesnt-stop-to-get-user-input

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!