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 bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Test if a var is a integer 1

Status
Not open for further replies.

bateman23

Programmer
Mar 2, 2001
145
DE
Hi everybody,

I know in VB there is the function isinteger() to test if a variable is a integer. Is there such a possibility in C++?

I'm searching for a function, or another possibility to test if a variable, or better a user input is an integer.

Thanks in advance,

bateman23 aka Daniel

---------------------------------------
Visit me @:
 
to test if user input is an integer just use

strspn(inputBuffer,"1234567890") == strlen(inputBuffer)

in a conditional statement.


matt
 
Ok - I should have said, that i'm very new to C++ ;-)
,so.....

my code actually looks like this:
cout << &quot;Type a number :&quot;;
cin >> number;

Now, here i have to check if that really is a number.
the code above doesn't work - at least i can't get it work.
Do i have to include a library, or does the varible has to be a special type? (now it's int)

Thanks,
Daniel
---------------------------------------
Visit me @:
 
Sorry.,.. here is a sample

Code:
#include <string.h>
#include <stdio.h>
#include <iostream.h>

int main()
{
   char buffer[32];
   cout<<&quot;Type a Number: &quot;;
   cin>>buffer;
   
   if(strspn(buffer,&quot;1234567890&quot;) == strlen(buffer))
   {
       cout<<&quot;Thank you for entering a number\r\n&quot;;
   }
   else
   {
      cout<<&quot;You need to learn what a number is!\r\n&quot;;
   }
}

That is the basics of it. This should compile if you just cut and paste... unless i forgot a semicolon somewhere :)

Matt
 
wow, thanks a lot for the very fast (!!) answer.
And even everything works.... a big star for you.

But - am i right - you can just perform this check with a
char-type ?
char buffer[32];
cin>>buffer;

Thanks, you helped me a lot
Daniel ---------------------------------------
Visit me @:
 
Theoretically, what is actually going on here is your looking at the ansi equivalent characters for the value. To pull the value out of the buffer, you will need to call atoi(buffer) which will return the value.

with cin, any base type can go after it.


int val;
char c;
char str[32];

cin>>val;
cin>>c;
cin>>str;

are all valid. The problems that occur is when the user enters a string into val.

Matt
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top