为什么里面的cin不会一直停下来获取用户输入? [英] Why cin inside while doesn't stop to get user input?

查看:328
本文介绍了为什么里面的cin不会一直停下来获取用户输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在开始使用C ++,所以我想这将是一个非常容易使用的新手问题。

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

那么,为什么 cin >> x行内是否不停止循环来获取用户输入(如果用户输入了字符而不是数字)?

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();
}

我几乎没有学习C ++的两天时间,所以我完全不了解真正的 cin是什么。我尝试使用 cin.sync()和 cin.clear(),但还是没有运气。
而且我知道不可能执行 cin = true或 cout<< cin之类的事情。

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

推荐答案

嗯,您的程序应该稍作修改

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!.";
}

这种方式可以正常工作。关于它的更多信息此处。通常,您需要清除cin中所有错误的内容。

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

这篇关于为什么里面的cin不会一直停下来获取用户输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆