1

I have a question regarding atoi. I am trying to use atoi to check if I can convert a character into a number, however, if my number is 0 how do I get around that? I understand that atoi returns 0 if it fails, but also returns the value of the number if it works, in which case 0 would fall under both categories.

If I were to use strtol instead, is there a way to check if the character in an array is >= to 0, or isn't/doesnt exist at all.

For instance, if my dynamic array consisted of {1 40 500}, and I try to strtol at position 8 (just out of bounds), I would like it to return NULL or some indication that atoi/strtol failed

FreeStyle4
  • 272
  • 6
  • 17
  • 2
    With `strtol`, you can use the `endptr` to determine whether the conversion succeeded. – user3386109 Mar 01 '16 at 05:40
  • 1
    Do you mean "1 40 500"? – nalzok Mar 01 '16 at 05:41
  • 2
    See [Correct way to use `strtol()`](https://stackoverflow.com/questions/14176123/correct-usage-of-strtol) for how to use `strtol()` correctly. It is not trivial. The information is available; it is just tricky to get all the conditions right. – Jonathan Leffler Mar 01 '16 at 05:42
  • `atoi()` and `strtol()` are used to convert char arrays to integer types. – nalzok Mar 01 '16 at 05:42

4 Answers4

2

You could instead use sscanf to read out the integer, that way just check the return value of sscanf to see if it found an integer or not

char a[] = "12";
char b[] = "abc";
int n = 0;

assert(sscanf(a, "%d", &n ) == 1);
assert(sscanf(b, "%d", &n ) == 0);
AndersK
  • 35,813
  • 6
  • 60
  • 86
1

if my number is 0 how do I get around that?

By not using atoi() in the 1st place. Use a member of the strto*() family of functions instead.

alk
  • 69,737
  • 10
  • 105
  • 255
1

By

dynamic array consisted of {1 40 500}

do you mean the C-string "1 40 500"? If that's the case, then a call to strtol at the null termination (position 8) will return in the 2nd parameter the same ptr passed to it:

char *s = "1 40 500";
char *ptr;
strtol(&s[8], &ptr, 10);
if (&s[8] == ptr) {
  // code executed if strtol was called at the null termination
}
Kyle
  • 21
  • 3
0
char n = '0';

if(atoi(n) == 0 && isdigit(n) ==1)
jmoerdyk
  • 5,544
  • 7
  • 38
  • 49
  • 2
    Remember that Stack Overflow isn't just intended to solve the immediate problem, but also to help future readers find solutions to similar problems, which requires understanding the underlying code. This is especially important for members of our community who are beginners, and not familiar with the syntax. Given that, **can you [edit] your answer to include an explanation of what you're doing** and why you believe it is the best approach? – Jeremy Caney May 19 '22 at 00:27