You are here:

C++/Input Validation in C++


QUESTION: how to validate user input? only double precision and integer are allowed.
This should not be allowed:
1. 123th...
2. _===\\
3. uuu67

This will be allowed
1. +67.89
2. -67.89
3. 67.89
4. 20

Please make a small program of this because I really find it hard... Thanks

ANSWER: Hi Dear Jade !

 A simple approach is just read the input as a string; scan the string , if you find any anomaly then report with an error , else if it found to be a valid integer of a float number then convert the string into integer and float using the built in functions atoi() and atof() respectively .

Tip : To identify float from integer before converting , just make sure if you encountered with a '.' symbol then use float ie atof() function to convert otherwise use atoi()

Thanks and Regards !
Prince M. Premnath

---------- FOLLOW-UP ----------

QUESTION: can you make a simple code out of this, i'm really confused

Dear Mr Jade !

Presenting you a simple code just to read a string and then convert into integer !

If it found to be a valid number , then the conversion will return the string as an integer else it will return 0 , same in case of float conversion !

You can add more constraints with this basic code.

void main()
int ino;
float fno;

char buffer[8];

cout<<"Enter a number";

ino = atoi(buffer);
  cerr<<"Error input in number ";


Get back to me in case of issues !

Thanks and Regards !
Prince M. Premnath


All Answers

Answers by Expert:

Ask Experts


Prince M. Premnath


Years of research in C/C++ Will bring you all facts regarding , OOPS , SVGA , MOUSE , BIOS , IVT , Feel free to query me :-)


More than 5 years


©2017 All rights reserved.