13

Here is the code

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

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?

Bo Persson
  • 90,663
  • 31
  • 146
  • 203
user1426900
  • 133
  • 1
  • 1
  • 5

2 Answers2

15

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;
}
Jonas Gröger
  • 1,558
  • 2
  • 21
  • 35
Jesse Good
  • 50,901
  • 14
  • 124
  • 166
0
#include <iostream>
#include<limits>
using namespace std;


int main() {
    
   int n;

    while (!(cin >> n)) {

        cin.clear();

        cin.ignore(numeric_limits<streamsize>::max(), '\n');

        cout << "Invalid input! Please try again with valid input: ";
    }
   return n;
}
  • i think this may help u understand easily – LUCKY FF Jul 20 '23 at 06:15
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jul 23 '23 at 17:12