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!

How to check if a string is an integer 1

Status
Not open for further replies.

suann

Programmer
Oct 24, 2005
2
US
Hi Guys,

I am new to C programming, How do I check if a string is an integer.

Eg., x="AB123456" -- In my program I want to print this is not an integer but if x="123456" I want to print this is an integer.

Any help greatly appreciated.

Thanks
Suann.
 
Thanks Dian for the quick response. What if I am in the middle of program. I am not reading value from the user input. Ex.,

char *Query;
Query=(char *)malloc(sizeof(char)*500);
strcpy(Query,"AB123456");

Now how do I know whether Query string contains only integers or contains both characters and integers. If it contains only integers I want to take some action or else different action.

Thanks again
Ann
 
Depending on your exact requirements (which are slightly unclear), strtol() might not do what you need.

You start by saying:
>>How do I check if a string is an integer
and then later say:
>>how do I know whether Query string contains only integers
These are two different requirements.

To achieve the former, you would use strtol() as shown in the last link supplied by Dian.

To achieve the latter, strtol() will not necessarily work, as the data could be any number of bytes in length, and the content may well exceed the value an integer (int) can store (INT_MAX or UINT_MAX, limits.h). Therefore, the validation method would be to walk through the array checking each byte using isdigit() (ctype.h) to determine if it is a numeric. Using this method, you can test any number of bytes.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top