Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

test for non-integer value

Status
Not open for further replies.

9871

Programmer
Aug 13, 2002
3
US
I define A of type integer. And ask the user to enter any number.
I am trying to write a test statement that that returns an error message if the user tries to enter a character instead of a number.

So far, I can't do it. Can someone help me, please?

Thanks
Khanh
 
If you use cin, then try out with cin.fail() after getting the user input. It might work.

zb
 
Hi,
cin.fail() seems not work.

maybe sizeof can be used depending on different sizes of fundamental types.But it can not separate int from long or float.
 
I think it is safer to store the input number into a string buffer, and then check each byte in it for error.
 
I have taken it into consideration.But it seems not easy to implement.I think this problem is really difficult to solve.
 

Here is how you can handle this:
Code:
#include <stdio.h>
#include <string.h>
#include <ctype.h>

bool IsInteger( char *number )
{
   int len = strlen( number );
   bool isnumber = true;
   int i = 0;

   while( i < len && isnumber )
   {
       if( isdigit( number[i] ) == 0 )
       {
            if( number[i] == '+' || number[i] == '-' )
            {
                if(  i + 1 > len - 1 || i - 1 >= 0 )
                {
                   isnumber = false;
                }
            }
            if( number[i] != '+' && number[i] != '-' )
            {
                isnumber = false;
            }
       }
       i++;
   }

   return isnumber;
}

void main()
{
    char number[20];
    
    printf(&quot;Enter a number: &quot;);
    gets(number);
    while( strlen( number ) == 0 )
    {
        printf(&quot;Please enter some input first:\n&quot;);
        gets(number);
    }

    if( IsInteger( number ) == false )
      printf(&quot;This is not a number.\n&quot;);
    else
      printf(&quot;Thanks for entering a number !\n&quot;);
}
 
Fancy C++ using STL and <algorithm>

#include <string>
#include <iostream>
#include <algorithm>
#include <cctype>
using namespace std;

int main()
{
// create a string
string s;

cin >> s;
cout << &quot;original: &quot; << s << endl;

int count = 0;

// check for nondigit
count = count_if(s.begin(),s.end(),isalpha);

if (count > 0)
cout << &quot;invalid alpha character&quot; << endl;

return 0;

}


 
jtm11 what if you have for input expressions like &quot;3.566&quot;,&quot;52 - 5556&quot;, &quot;569*12+55 - 2.3665&quot; etc

would those expressions be considered to be integers ?
 
Excellent catch. How about this instead:

#include <string>
#include <iostream>
#include <algorithm>
#include <cctype>
using namespace std;

int main()
{
// create a string
string s;

cin >> s;
cout << &quot;original: &quot; << s << endl;

int count = 0;

// check for nondigit
count = count_if(s.begin(),s.end(),isdigit);

if (count != s.size())
cout << &quot;invalid alpha character&quot; << endl;

return 0;

}
 
This looks better than before.
But what about expressions such as &quot;-556&quot;,&quot;+665&quot; etc they should be acceptable integers too. No ?
 
Leibnitz,

I found a workaround using a custom function to test instead of isdigit, but then remembered that the following is also a valid integer:

3.54E+120

So I think your solution provides a better foundation for a professional-grade approach, but scientific notation is a valid numeric format, and seeing as how I am a numeric programmer myself, I would want it to be handled by the software.

As it stands, I have come up with an algorithm to detect UNSIGNED integers. Not bad, but not great.
 

But this just checks the input.I want an integer or other kinds of numeric values but not a string.
Is there a method that can use the input as numeric values at the same time it can be checked? **************************************
I love tek-tips.com very,very,very,very,... much!
 
This is pretty simple to do,you just have to use the function &quot;atoi&quot;.

#include <stdlib.h>
....
char number[20];
int Number;
.....
...
Number = atoi(number);
....
 
Test for non-integer values:

Consider some cases:
Case-1: If you want to check user input through input device, such as keyboard then monitor kbhit() in Dossy application or WM_KEYDOWN message in windows application and check that user has pressed the keys from 0..9, '.', +|-

Case-2: I am sure you don't want to check case-1. so consider the following.

int x, y, z;
x = 65; // value of x is 65
y = 'A'; // value of y is 65
z = -'A'; // value of z is -65

Nothing amazing in C language, because in C, int and byte are fundamental data types which takes 2 byte and 1 byte allocation space in memory in 16 bit computers. Hence, compiler can put 1 byte or 8 bits easily in to the lower register i.e. AL But reverse is not true. Also, C is not not strong type checking language. Consider the following.

int x, y, z;
char ch;
x = 'A; // value of x is 65
ch = x; // value of ch is ??? ==> 'A'

In this case compiler will not even issue a warning at assignment statement ch = x; because int and char both are signed types, but you will loose lower byte of variable x.

Case-3: Now all these discussion you want a data type which will hold only an integer numerical value and nothing else. For this consider the OOPS. In C++, you can create your own data type from the basic data types and design and use it the way you want. Consider the following object TInt instead of standard integer data type int.

class TInt {
INT nNum;
public:
TInt():nNum(0) {}
TInt(INT n): nNum(n) {}
TInt(const TInt& rhs) { nNum = rhs.nNum; }

operator int() const { return (int)nNum; }
TInt &operator =(const TInt& rhs) { nNum = rhs.nNum; return *this; }
TInt &operator =(INT n) { nNum = n; return *this; }
TInt &operator =(char c) { TRACE(&quot;some thing is wrong.\n&quot;); return *this; }

TInt &operator +=(const TInt &rhs) { nNum += rhs.nNum; return *this; }
TInt &operator -=(const TInt &rhs) { nNum -= rhs.nNum; return *this; }
TInt &operator *=(const TInt &rhs) { nNum *= rhs.nNum; return *this; }
TInt &operator /=(const TInt &rhs) { nNum /= rhs.nNum; return *this; }
};

Usage of type TInt:

TInt num1, num2, num3;

num1 = 3;
num2 = num1;
num3 += num2;
num1 = 3 + num2 * num1 + 5;

You can have all the possible operators in this object. But for your problem consider the following two operator functions.

TInt &operator =(INT n) { nNum = n; return *this; }
TInt &operator =(char c) { TRACE(&quot;some thing is wrong.\n&quot;); return *this; }

Yes, you are right. Now when you will say...

TInt num1, num2;
num1 = 'A'; // this will display a warning message.
num2 = 65; // no warning

Suhas Tambe.
Thu. Aug. 15, 2002
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top