You are here:

C++/Input Validation in C++

Advertisement


Question
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

Answer
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.

#include<iostream.h>
#include<stdlib.h>
void main()
{
int ino;
float fno;

char buffer[8];

cout<<"Enter a number";
cin>>buffer;

ino = atoi(buffer);
if(!ino)
  cerr<<"Error input in number ";
else
  cout<<ino;

}

Get back to me in case of issues !

Thanks and Regards !
Prince M. Premnath

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Prince M. Premnath

Expertise

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

Experience

More than 5 years

Education/Credentials
MCA

©2016 About.com. All rights reserved.