Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C++
how can we check the any data type value entered by the user is correct or not? or if any user enter in this program the integer value then the program will run otherwise if he enters a floating value in place of integer an exception should occur. How it will be possible with an if condition?What should i write in if condition for type checking ?
 
void main()
{
   int val;
   try
   {
      cout<<"Enter an value :";
      cin>>val;
      if(  )
      {
          throw 2;
      }
      else
      {
          cout<<"You entered an integer value";
      }
   }
   catch(int x)
   { 
          cout<<"You should eneter an integer value..";
   }
   getch();
}
Posted 21-Dec-11 21:20pm
Edited 21-Dec-11 21:24pm
v3
Comments
Karthik Harve at 22-Dec-11 3:23am
   
[Edit] pre tags added.
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

Probably the best way, in such a simple case is:
  1. Accept a string as input.
  2. Scan yourself the string looking for invalid characters.
  Permalink  
Comments
Ashutosh_g at 22-Dec-11 3:44am
   
is the string a data type in c++?
CPallini at 22-Dec-11 3:55am
   
Nope, but is a class of the STL library, you may write:
 
string s;
cin >> s;
Albert Holguin at 22-Dec-11 11:10am
   
this is a simple, broad way of doing this... +5
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 3

Good question, that deserves a more elaborated answer.
 

The C++ I/O model

The idea behind the C++ I/O is that Input and Output are represented as two infinite sequence of elementary type (generically called "character", and implemented though char or wcahr_t) retrievable in sequence and possibly convertible into all the built-in type or STL basic types (strings) across a set of procedure provided through "facets" of a "locale class" whose default instance is implicitly "imbued" into the stream classes that in tur provide the client interface (the << and >> operators).
 
Where does those "infinite sequence of characters" (long name for "stream") comes from or go to is left unspecified by the language.
 
That said, a "general purpose program" should not assume they are necessarily binded to whatever end-use handled device: the could bi files, network sockets, whatever thing that can "spits out" or "drain off" characters.
 
Because of these facts, C++ I/O is relatively poor: if an input satisfy the type it is designated, is read, otherwise the stream is blocked into an error condition to be somehow analised a reset.
For very trivial task (or for task the input format is rigidly defined) this can be enough, bot for more complex tasks (where input can be somehow erroneous or non predictable or not organized in a rigid sequence) C++ I/O model has almost no support.

The user model

There are essentially three types of applications (plus some more derivative):
  1. Computer driven programs
  2. User driven programs
  3. Event driven programs

Computer driven

Are programs where the computer tells the user step by step what data it wants. It can be emulated by mapping C++ streams to a user console, assuming the terminal as a display for output and a keyboard as a character generator. This is what cin and cout do.
The user is required to strictly conform to the computer expectation.
Robust program checks for error condition, reset the stream, cleanup the buffer and ask to re-enter the required data.
 
Note that this is already a violation of the standard C++ model: in the C++ model input and output are unrelated. The input is not a "reaction to an output" (not something C++ I/O is aware of).
Imagine to read 10 number from a file. If one of them isn't readable as a number, what dues it mean "cleanup the buffer and ask again"? is "reset and skip the char up to the next line delimiter and retry" a good error recovery? Or are you just misreading the values? A C++ most general program is not necessarily designed to be managed by a user.
 

User driven programs

A "user interfaced" program must go one step ahead the standard input, and be somehow more "semantic". Not just a "converter" (typically from text to number and number to text) but a real "interpreter" of a "language" that is defined by the action a user can do, and a recover from incongruent actions.
Here is when the >> operator is dismissed in favor of getline, and the text is retrieved unconverted from cin (thus making all the iostream class useless overhead) and analyzed before being finally converted properly (may be through another stream binded to the string: sstream).
And this is the typical situation (see here[^])
The program flow is broken in a set of functionalities the user activates by supplying commands. It typically happens trough textual strings the user is supposed to type. The program itself is a (sort of ) loop that resamble a command interpreter: A string is read, analyzed, "interpreted" and if a command is recognized the corresponding function is called. The loop continue until a "quit" command is given.
 
In this context, the standard input can be not as good as it may seem: a buffering mechanism that block the flow until a "end of line" if reached may be not enough reactive.
 

event driven program

Here is where the C++ standard input model loose all its attractive: program whose main loop has to react to every single typed character (an may be even to other user manipulated peripheral, like a mouse or a touch or multitouch surface) cannot fit the C++ standard input model, and even the output model becomes to be inadequate (may be it cannot be anymore a simple "sequence").
What is bad, here, is that C++ has ... no "standardized model" to work with, and hence you have to go down to the underlying platform API, or use one of the multi-platform frameworks available. The other dramatic aspect is that almost all of them are based on what C++ was 10 or more years ago, looking much more "C with classes" that "modern C++".
An this is a gap that has to be somehow filled.
 

coming back to OP question

You are actually running a "computer driven program", but you also want "robustness" against common error.
 
Some suggestions I can give:
 
istream can be used as a boolean value that is "false" if not in "good" state (essentially: if something went wrong during the last read)
so:
   cin>>val;
   if(!cin) { /*handle error condition */}
Can be a good way to identify input incongruence.
But the stream, at that point, is in "bad" state.
This requires a call to cin.clear() and then read all and ignore the "rubbish"
while(true)
{
   cout<<"Enter an value :";
   cin >> val;
   if(!cin)
   {
      cin.clear();
      cin.ignore(numeric_limits<streamsize>::max(), '\n');
      cout<<"Bad input. ";
   }
   else
      break;
}
cout<< "You entered "<<val <<endl;
Here the program loops until the input is satisfied.
This is the most it can be done by still being aligned to the C++ standard input model.
 
Note also that I didn't use exceptions here. Unless if you are experiencing with exception, don't use them that way: the fact a user can mistype a value is all but "exceptional", and -in general- catching an exception in the same context it has been thrown is pointless. You can just use normal program structures.
The idea of exception is that something wrong happens in your context without you can do anything to correct/prevent it. So that you throw with the idea that what called you will "catch", may be some level back in the stack, where more information are known about the purpose of the (failed) action that where required.
  Permalink  
v2
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

I use a method called validate(string myTempString){} but this is when i transmite a string.
in your case if you enter something else(like a double) it would trow a exception.
so you can do
try
{
cin>>val;
}
catch()
{
trow 2;
}
  Permalink  
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
0 OriginalGriff 248
1 Maciej Los 210
2 Sergey Alexandrovich Kryukov 160
3 Peter Leow 155
4 George Jonsson 135


Advertise | Privacy | Mobile
Web02 | 2.8.140709.1 | Last Updated 22 Dec 2011
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid