Integer and floating point number validation

  • (2 Pages)
  • +
  • 1
  • 2

28 Replies - 7367 Views - Last Post: 03 March 2010 - 09:44 AM Rate Topic: -----

#1 Tapas Bose  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 23
  • View blog
  • Posts: 472
  • Joined: 09-December 09

Integer and floating point number validation

Posted 03 March 2010 - 12:57 AM

Hallo. I am trying to validate integer and floating point number.
The code for integer validation is :
int getNumber()
{
	long Value;
	bool correctInput = false;

	while(!correctInput)
	{
		char *endPtr;
		string Str;
		Value = 0;

		cout << "\n";
		cin.sync();
		cout << "  Enter an integer : ";
		getline(cin, Str, '\n');
		cout << "\n";
		
    		errno = 0;
    		Value = strtol(Str.c_str(), &endPtr, 10);
    		
    		// check if there is any overflow or underflow
    		
    		if ((errno == ERANGE && (Value == LONG_MAX || Value == LONG_MIN)) || (errno != 0 && Value == 0))
   		{
        		cerr << "  Numerical result out of range." << endl;
        		correctInput = false;
    		}
    		
    		// check wheather input string containg any character
    		
   		else if (endPtr == Str || *endPtr != '\0')
   		{
        		cerr << "  Invalid input." << endl;
        		correctInput = false;
    		}
    		
    		// otherwise correct input
    		
		else
		{
			correctInput = true;
		}
	}

	return Value;
}

Its output is fine. Similarly I try to write the code for floating point number validation :
int getNumber()
{
	double Value;
	bool correctInput = false;

	while(!correctInput)
	{
		char *endPtr;
		string Str;
		Value = 0;

		cout << "\n";
		cin.sync();
		cout << "  Enter a Number : ";
		getline(cin, Str, '\n');
		cout << "\n";

    		errno = 0;
    		Value = strtod(Str.c_str(), &endPtr);
    		
    		// check if there is any overflow or underflow
    		
    		if ((errno == ERANGE && (Value == HUGE_VALF || Value == HUGE_VALL)) || (errno != 0 && Value == 0))
   		{
        		cerr << "  Numerical result out of range." << endl;
        		correctInput = false;
    		}
    		
    		// check wheather input string containg any character
    		
   		else if (endPtr == Str || *endPtr != '\0')
   		{
        		cerr << "  Invalid input." << endl;
        		correctInput = false;
    		}
    		
    		// otherwise correct input
    		
		else
		{
			correctInput = true;
		}
	}

	return Value;
}

But the output for floating point number is something wrong, like:
tapas@My-Child:~/Programming/Input Validation$ ./"Float Input Validation.o"

Enter a Number : 123

You have entered : 123 <--Ok

tapas@My-Child:~/Programming/Input Validation$ ./"Float Input Validation.o"

Enter a Number : 12.3

You have entered : 12 <--Not ok (It will be 12.3)

tapas@My-Child:~/Programming/Input Validation$ ./"Float Input Validation.o"

Enter a Number : 12e3

You have entered : 12000 <--Ok

tapas@My-Child:~/Programming/Input Validation$ ./"Float Input Validation.o"

Enter a Number : 12e-3

You have entered : 0 <--Not ok (It will be 0.012)

tapas@My-Child:~/Programming/Input Validation$ ./"Float Input Validation.o"

Enter a Number : 12e-1

You have entered : 1 <--Not ok (It will be 1.2)

Another problem in the output is that if I press enter without giving any input it displays Invalid input. This problem can be solved using cin >> Str; instead of getline(cin, Str, '\n'); but if I use cin >> Str and give input 12 2 then it displays 12 because cin ignores whitespace, but 12 2 is an invalid input, because there can not be any space between numbers.
Is there any mistake in my code? Please help.

For both cases main function is:
int main()
{
	cout << "  You have entered : " << getNumber() << endl << endl;
	return 0;
}

This post has been edited by Tapas Bose: 03 March 2010 - 01:03 AM


Is This A Good Question/Topic? 0
  • +

Replies To: Integer and floating point number validation

#2 Ferencn  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 71
  • View blog
  • Posts: 322
  • Joined: 01-February 10

Re: Integer and floating point number validation

Posted 03 March 2010 - 01:10 AM

In case of the float validator change your function so it returns a double!
int getNumber()
{



double getNumber()
{

Otherwise the double will be converted to an int, before being returned. And that is what is happening
Was This Post Helpful? 1
  • +
  • -

#3 Tapas Bose  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 23
  • View blog
  • Posts: 472
  • Joined: 09-December 09

Re: Integer and floating point number validation

Posted 03 March 2010 - 01:19 AM

What a silly mistake!! I am really ashamed on me. Actually I copy and pest my previously written integer input validation code for floating point number validation.
Sir what about another problem? How can I resolve it?

This post has been edited by Tapas Bose: 03 March 2010 - 01:22 AM

Was This Post Helpful? 0
  • +
  • -

#4 Ferencn  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 71
  • View blog
  • Posts: 322
  • Joined: 01-February 10

Re: Integer and floating point number validation

Posted 03 March 2010 - 01:30 AM

You could try to do a validation on your Str, and when it is empty (Str.isempty()) print out a message (e.g. that theh input is empty), do not try to convert it and ask for another input.

This post has been edited by Ferencn: 03 March 2010 - 01:30 AM

Was This Post Helpful? 1
  • +
  • -

#5 Tapas Bose  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 23
  • View blog
  • Posts: 472
  • Joined: 09-December 09

Re: Integer and floating point number validation

Posted 03 March 2010 - 01:50 AM

View PostFerencn, on 03 March 2010 - 12:30 AM, said:

You could try to do a validation on your Str, and when it is empty (Str.isempty()) print out a message (e.g. that theh input is empty), do not try to convert it and ask for another input.

So the code for integer input validation is now become :
#include <cstdlib>
#include <climits>
#include <cerrno>
#include <iostream>
#include <string>

using namespace std;

int getIntNumber()
{
	long Value;
	bool correctInput = false;

	while(!correctInput)
	{
		char *endPtr;
		string Str;
		Value = 0;

		cout << "\n";
		cin.sync();
		cout << "  Enter an integer : ";
		
		getline(cin, Str, '\n');
		cout << "\n";
		
		if (Str.empty())
		{
			correctInput = false;
			cerr << "  Input is empty." << endl;
		}
		else
		{
	    		errno = 0;
	    		Value = strtol(Str.c_str(), &endPtr, 10);
	    		
	    		// check if there is any overflow or underflow
	    		
	    		if ((errno == ERANGE && (Value == LONG_MAX || Value == LONG_MIN)) || (errno != 0 && Value == 0))
	   		{
	        		cerr << "  Numerical result out of range." << endl;
	        		correctInput = false;
	    		}
	    		
	    		// check wheather input string containg any character
	    		
	   		else if (endPtr == Str || *endPtr != '\0')
	   		{
	        		cerr << "  Invalid input." << endl;
	        		correctInput = false;
	    		}
	    		
	    		// otherwise correct input
	    		
			else
			{
				correctInput = true;
			}
		}
	}

	return Value;
}

int main()
{
	cout << "  You have entered : " << getIntNumber() << endl << endl;
	return 0;
}

Sir I have another integer input validation code :
#include <iostream>
#include <string>
#include <cstdlib>
#include <sstream>

using namespace std;

int getNumber()
{
        string number;
        
        bool digit = false;
        
        while(!digit)
        {
                digit = true;

                cin.sync();
                
		cout << "\n";
                cout <<"  Enter an integer : ";
                cin >> number;
        	cout << "\n";
        	
        	int i = (number[0] == '-' || number[0] == '+') ? 1 : 0;
        	
                for(; i<number.length(); i++)
                {
                        if(!isdigit(number[i]))
                        {
                                digit = false;               
                                cout <<"  Invalid input." << endl;
                                break;
                        }
                }
        }
        
        return atol(number.c_str());
}

int main()
{
	cout << "  You have entered : " << getNumber() << endl << endl;
        cin.ignore();
        return 0;
}

Which one is better?
Was This Post Helpful? 0
  • +
  • -

#6 Ferencn  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 71
  • View blog
  • Posts: 322
  • Joined: 01-February 10

Re: Integer and floating point number validation

Posted 03 March 2010 - 02:13 AM

Your 2nd approach gives you more flexibility and possibilities for (constructive) feedback, but will be a litte more complex to implement for floats.
The strtol and atol functions just return a number (or not) and give little to no feedback.
Was This Post Helpful? 1
  • +
  • -

#7 Tapas Bose  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 23
  • View blog
  • Posts: 472
  • Joined: 09-December 09

Re: Integer and floating point number validation

Posted 03 March 2010 - 02:35 AM

View PostFerencn, on 03 March 2010 - 01:13 AM, said:

Your 2nd approach gives you more flexibility and possibilities for (constructive) feedback, but will be a litte more complex to implement for floats.
The strtol and atol functions just return a number (or not) and give little to no feedback.

I am going to write a header namely inval.h, whose job is to check whether an input is valid or not and I want to include two functions in my first post on this topic. Will it be okay?

This post has been edited by Tapas Bose: 03 March 2010 - 02:37 AM

Was This Post Helpful? 0
  • +
  • -

#8 Ferencn  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 71
  • View blog
  • Posts: 322
  • Joined: 01-February 10

Re: Integer and floating point number validation

Posted 03 March 2010 - 02:47 AM

It never hurts to put frequently used functions or classes in a header and cpp file for inclusion in other projects... Be aware that changes in those files may affect all your projects...
Was This Post Helpful? 1
  • +
  • -

#9 Tapas Bose  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 23
  • View blog
  • Posts: 472
  • Joined: 09-December 09

Re: Integer and floating point number validation

Posted 03 March 2010 - 02:52 AM

Thank you sir.
Was This Post Helpful? 0
  • +
  • -

#10 Tapas Bose  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 23
  • View blog
  • Posts: 472
  • Joined: 09-December 09

Re: Integer and floating point number validation

Posted 03 March 2010 - 03:31 AM

Here is my header :
#ifndef _INVAL
#define _INVAL

#include <iostream>
#include <cstdlib>
#include <climits>
#include <cerrno>
#include <string>
#include <cmath>

using namespace std;

int getInt()
{
	long Value;
	bool correctInput = false;

	while(!correctInput)
	{
		char *endPtr;
		string Str;
		Value = 0;

		cout << "\n";
		cin.sync();
		cout << "  Enter an integer : ";
		
		getline(cin, Str, '\n');
		cout << "\n";
		
		if (Str.empty())
		{
			correctInput = false;
			cerr << "  Input is empty.";
			cin.get();
	        	system("clear");
		}
		else
		{
	    		errno = 0;
	    		Value = strtol(Str.c_str(), &endPtr, 10);
	    		
	    		// check if there is any overflow or underflow
	    		
	    		if ((errno == ERANGE && (Value == LONG_MAX || Value == LONG_MIN)) || (errno != 0 && Value == 0))
	   		{
	        		cerr << "  Numerical result out of range.";
	        		cin.get();
	        		system("clear");
	        		correctInput = false;
	    		}
	    		
	    		// check whether input string containg any character
	    		
	   		else if (endPtr == Str || *endPtr != '\0')
	   		{
	        		cerr << "  Invalid input.";
	        		cin.get();
	        		system("clear");
	        		correctInput = false;
	    		}
	    		
	    		// otherwise correct input
	    		
			else
			{
				correctInput = true;
			}
		}
	}

	return Value;
}

double getFloat()
{
	double Value;
	bool correctInput = false;

	while(!correctInput)
	{
		char *endPtr;
		string Str;
		Value = 0;

		cout << "\n";
		cin.sync();
		cout << "  Enter a Number : ";
		getline(cin, Str, '\n');
		cout << "\n";

		if (Str.empty())
		{
			correctInput = false;
			cerr << "  Input is empty.";
			cin.get();
	        	system("clear");
		}
		else
		{
	    		errno = 0;
	    		Value = strtod(Str.c_str(), &endPtr);
	    		
	    		// check if there is any overflow or underflow
	    		
	    		if ((errno == ERANGE && (Value == HUGE_VALF || Value == HUGE_VALL)) || (errno != 0 && Value == 0))
	   		{
	        		cerr << "  Numerical result out of range.";
	        		correctInput = false;
	        		cin.get();
		        	system("clear");
	    		}
	    		
	    		// check whether input string containg any character
	    		
	   		else if (endPtr == Str || *endPtr != '\0')
	   		{
	        		cerr << "  Invalid input.";
	        		correctInput = false;
	        		cin.get();
	        		system("clear");
	    		}
	    		
	    		// otherwise correct input
	    		
			else
			{
				correctInput = true;
			}
		}
	}

	return Value;
}

#endif


And this is the main function :
#include <iostream>
#include "inval.h"

int main()
{
	system("clear");
	cout << "  You have entered : " << getInt();
	cin.get();
	system("clear");
	cout << "  You have entered : " << getFloat() << endl << endl;
	return 0;
}

Can you please check this sir? The output is okay and no error.
One more question : in the main function before executing cout << " You have entered : " , main call getInt(), similarly for getFloat(). How it is possible?

This post has been edited by Tapas Bose: 03 March 2010 - 03:40 AM

Was This Post Helpful? 0
  • +
  • -

#11 Ferencn  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 71
  • View blog
  • Posts: 322
  • Joined: 01-February 10

Re: Integer and floating point number validation

Posted 03 March 2010 - 03:41 AM

I have not checked all your code, but to answer your last question:
First assign the input to a variable...
This way you can also use the value later in your code.

int main()
{
        system("clear");
        int myinteger = getInt();
        cout << "  You have entered : " << myinteger;
        cin.get();
        system("clear");

        float myfloat = getFloat();
        cout << "  You have entered : " << myfloat << endl << endl;
        return 0;
}


This post has been edited by Ferencn: 03 March 2010 - 03:42 AM

Was This Post Helpful? 0
  • +
  • -

#12 Tapas Bose  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 23
  • View blog
  • Posts: 472
  • Joined: 09-December 09

Re: Integer and floating point number validation

Posted 03 March 2010 - 03:46 AM

View PostFerencn, on 03 March 2010 - 02:41 AM, said:

I have not checked all your code, but to answer your last question:
First assign the input to a variable...
This way you can also use the value later in your code.

int main()
{
        system("clear");
        int myinteger = getInt();
        cout << "  You have entered : " << myinteger;
        cin.get();
        system("clear");

        float myfloat = getFloat();
        cout << "  You have entered : " << myfloat << endl << endl;
        return 0;
}


Yes sir I know this, at first I did it as you say. Then I think if I change it as in my code, what will happen. I saw it also works. So I want to know how it is working, before executing cout main call getInt() and getFloat(), what is the mechanism behind this behavior? In actual implementation I will do it as you say.

This post has been edited by Tapas Bose: 03 March 2010 - 03:48 AM

Was This Post Helpful? 0
  • +
  • -

#13 Ferencn  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 71
  • View blog
  • Posts: 322
  • Joined: 01-February 10

Re: Integer and floating point number validation

Posted 03 March 2010 - 04:07 AM

The compiler will process the line
cout << "  You have entered : " << getInt();

from right to left.
So it will do the call to getInt() and process all it's output, before sending the string "You have entered : " and the result to cout.

This post has been edited by Ferencn: 03 March 2010 - 04:09 AM

Was This Post Helpful? 1
  • +
  • -

#14 Tapas Bose  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 23
  • View blog
  • Posts: 472
  • Joined: 09-December 09

Re: Integer and floating point number validation

Posted 03 March 2010 - 04:23 AM

View PostFerencn, on 03 March 2010 - 03:07 AM, said:

The compiler will process the line
cout << "  You have entered : " << getInt();

from right to left.
So it will do the call to getInt() and process all it's output, before sending the string "You have entered : " and the result to cout.

Okay sir I understand. That means direction of processing a line is not fixed. I read in my book that while processing assignment operation compiler goes from right to left. But in this case "cout" is processed from right to left, in some other "cout" cases it may be left to right. So the direction of processing "cout" in a program is not fixed. Am I right sir? Is there any rule of such processing?
Was This Post Helpful? 0
  • +
  • -

#15 Ferencn  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 71
  • View blog
  • Posts: 322
  • Joined: 01-February 10

Re: Integer and floating point number validation

Posted 03 March 2010 - 04:41 AM

The '<<' can be seen as a special assignment or operator; you send/assign some output data to cout.
So it gets processed from right to left as well.

Think of the command as: cout = "You entered" + getInt();

If you are unsure about the order, just split your cout command into separate ones, so you are certain they will be executed in the desired order.

This post has been edited by Ferencn: 03 March 2010 - 04:46 AM

Was This Post Helpful? 1
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2