如何使cin只收数字 [英] How to make cin take only numbers

查看:220
本文介绍了如何使cin只收数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是代码

double enter_number()
{
  double number;
  while(1)
  {

        cin>>number;
        if(cin.fail())
        {
            cin.clear();
            cin.ignore(numeric_limits<streamsize>::max(), '\n');
            cout << "Invalid input " << endl;
        }
        else
        break;
        cout<<"Try again"<<endl;
  }
  return number;
}

我的问题是当我输入像1x,输入,但不会注意到为另一次运行留下的字符。
有任何方法如何使它与任何实数工作。 1.8

My problem is that when I enter something like 1x, then 1 is taken as input without noticing the character that is left out for another run. Is there any way how to make it work with any real number e.g. 1.8?

推荐答案

我会使用 std :: getline c $ c> std :: string 读取整行,然后只有当你可以将整行转换为double时才跳出循环。

I would use std::getline and std::string to read the whole line and then only break out of the loop when you can convert the entire line to a double.

#include <string>
#include <sstream>

int main()
{
    std::string line;
    double d;
    while (std::getline(std::cin, line))
    {
        std::stringstream ss(line);
        if (ss >> d)
        {
            if (ss.eof())
            {   // Success
                break;
            }
        }
        std::cout << "Error!" << std::endl;
    }
    std::cout << "Finally: " << d << std::endl;
}

这篇关于如何使cin只收数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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