Click here to Skip to main content
15,883,749 members
Please Sign up or sign in to vote.
5.00/5 (3 votes)
See more:
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 ?

C++
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
Updated 21-Dec-11 21:24pm
v3
Comments
Karthik Harve 22-Dec-11 3:23am    
[Edit] pre tags added.

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.
 
Share this answer
 
Comments
Ashutosh_g 22-Dec-11 3:44am    
is the string a data type in c++?
CPallini 22-Dec-11 3:55am    
Nope, but is a class of the STL library, you may write:

string s;
cin >> s;
Albert Holguin 22-Dec-11 11:10am    
this is a simple, broad way of doing this... +5
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.
 
Share this answer
 
v2
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
C++
try
{
cin>>val;
}
catch()
{
trow 2;
}
 
Share this answer
 
v2

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

  Print Answers RSS


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900