john doe
john doe

Reputation: 1

Is there a way to restrict input to integer/double in this format in c++

I am trying to make a simple calculator in c++. In my first version, I had menu based system and i asked for input one after other so it was easy to validate for integer. However, i realised i can get the user to enter their question in the format you enter on a real calculator.

double first;
char choice;
double second;

cin >> first >> choice >> second;

However now I am stuck on how i can check because most of the solution i have looked at follow this format, which i do not know how i can implement because my cin takes in 3 pieces of data.

int x;
cin >> x;

if (!cin) 
{
    // not a number
}

Upvotes: 0

Views: 511

Answers (2)

Davislor
Davislor

Reputation: 15144

The scanf() function from <stdio.h> or <cstdio> gives you more fine-tuned control over what kind of input you accept. Another option is to read in a line of input as a std::string or char buffer, then parse the line to see if it’s valid input.

Upvotes: 0

R Sahu
R Sahu

Reputation: 206657

You cannot restrict what the user types at a terminal. The best thing you can do is detect that the input is not appropriate, and ask for the input again.

while ( !(cin >> first) )
{
   cout << "Please an enter a floating point number: "
   cin.clear();
   cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}

Do the same thing for the other numbers.

Upvotes: 2

Related Questions