AllExperts > Experts 
Search      

C++

Volunteer
Answers to thousands of questions
 Home · More Questions · Answer Library  · Encyclopedia ·
More C++ Answers
Question Library

Ask a question about C++
Volunteer
Experts of the Month
Expert Login

Awards

About Us
Tell friends
Link to Us
Disclaimer

 
 
 
 
About Prince M. Premnath
Expertise
Years of research in Turbo C 3.0 Will bring you all facts regarding , OOPS , SVGA , MOUSE , BIOS , IVT , Be free to ask questions.

Experience
Research For 3 years.

Education/Credentials
MCA

 
   

You are here:  Experts > Computing/Technology > C/C++ > C++ > Input Validation in C++

Topic: C++



Expert: Prince M. Premnath
Date: 4/15/2008
Subject: Input Validation in C++

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

View Follow-Ups    Add to this Answer    Ask a Question



  Rate this Answer
   Was this answer helpful?
Not at allDefinitely              
   12345  

     
About Us | Advertise on This Site | User Agreement | Privacy Policy | Help
Copyright  © 2008 About, Inc. About and About.com are registered trademarks of About, Inc. The About logo is a trademark of About, Inc. All rights reserved.