2

A beginner question !

How to oblige the user to only input a number (int,float,long..) so he cannot input a char or a string when you're waiting for a number :D thanks

  • If you're asking for [tag:c++], take a look at my answer here: [Filling structure from a file](http://stackoverflow.com/questions/22518465/filling-structure-from-a-file). The technique explained allows to check any field input operation separately, without putting the original input stream to `fail()` state when reading a wrong input field value. But that's after input. If you want to restrict the accepted characters at input at all you might find [this](http://stackoverflow.com/questions/22518983/why-does-cin-need-newline-to-be-entered) helpful. – πάντα ῥεῖ Mar 19 '14 at 22:03

2 Answers2

0

There aren't any standard C/C++ libraries to prevent the user from entering a string where a number is expected.

If you are using scanf or fscanf, you can check the value returned from the function to make sure that you were able to read the expected number of data.

If you are using std::cin or std::ifstream, you use fail() to check whether the operation succeeded or not.

R Sahu
  • 204,454
  • 14
  • 159
  • 270
0

In general input validation can be done in two distinct ways:

  1. Validate input after the user entered his input, and display an appropriate message, along asking the user to re-enter valid input.
  2. Keep a state machine (FSM) that knows which input format is expected at a particular point . When the user is going to input particular characters, these are checked to fit for the current state's rules.

The 1st solution is easy to do, because you can check input operations for particular fields:

std::istream& is = <reference to any valid input stream>;

double value;
if(!(is >> value)) {
    // Issue error message
}

The 2nd solution needs to peek for characters as they are typed in, and are immediately checked to become part of the input (and be echoed at the tty), or not. That's not possible in a simple, OS independent way.
Though there are techniques available, that enable you to restrict character inputs from std::cin according your current parser FSM state. Check this post for more information about how this can be achieved.

Community
  • 1
  • 1
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190