How to make cin take only numbers

后端 未结 4 1092
青春惊慌失措
青春惊慌失措 2020-11-22 07:30

Here is the code

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

        cin>>number;
        if(cin.fail())
        {
            cin.clear()         


        
4条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-22 07:53

    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 
    #include 
    
    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;
    }
    

提交回复
热议问题