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!

Intger or string

Status
Not open for further replies.

countdrak

Programmer
Jun 20, 2003
358
US

On reading a value from a file, using fgets, I need to determine if the value is a string or integer before I do an "atoi".

I have noticed on "atoi"ing a string, I get zero all the time. But there has to be a better check....is there?

Thanks.
 
It will still return a 0 if not able to convert.

My situation is

if fgets_val == string
req_value = DEFAULT;
else
req_value == covert_to_int(fgets_val);

So if the fgets_val is 0 or string should take me to different values, unlike in strtol.

 
That example is good, but shouldn't you also check if errno was set to ERANGE (in case the user entered a number too big or small for a long)?
 
Well, implement your own int parser, it's so simple - for example:
Code:
/** Returns:
 *  - 0 - not an integer.
 *  - 1 - integer + garbage tail.
 *  - 2 - true integer!
 */
int isint(const char* str)
{
  static const char ws[] = " \t\r\n";
  static const char dd[] = "0123456789";
  int	n, res = 0;
  if (!str || !*str)
     return 0;
  str += strspn(str,ws);
  if (*str == '-' || *str == '+')
     ++str;
  n = strspn(str,dd);
  if (n)
  {
     str += n;
     str += strspn(str,ws);
     res = (*str?1:2);
  }
  return res;
}
You may replace strspn() call by an explicit scan loops.
On rc 1 and 2 case atoi() returns int value (for example, it returns 3 for 3.14 arg).
 
Of course U mean

req_value = covert_to_int(fgets_val);

NOT

req_value == covert_to_int(fgets_val);

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top