atoi()
will return 0
if conversion cannot be performed. Look here.
The string "score: 34"
cannot be converted to a valid int
. So atoi()
returns 0
.
If there's nothing else after the 34
in your string, you could do
printf("score: %d\n",atoi(conv + 7));
This would give 34
. conv + 7
points to the string "34"
. It is equivalent of conv + strlen("score: ")
.
Use of strtol()
instead of atoi()
might be better here.
You can find what exactly went wrong more easily with strtol()
.
You could use it like
long rv=strtol(conv, &ptr, 10);
where ptr
is of type char *
or just
rv=strtol(conv, NULL, 10);
If conv
is "score: 34"
here, 0
is returned and ptr
will point to start of conv
.
Note that strtol()
returns a long
and not an int
.
If the range of int
is less than that of long
, you may want to check if the returned value is greater than the biggest int
which is INT_MAX
for signed int. INT_MAX
is in limits.h
.
If overflow occurred because of the number in string being too large to be represented in a long
, errno
will be set to ERANGE
(it's in errno.h
).
long rv=strtol(str, NULL, 10);
if(rv>INT_MAX || rv<INT_MIN || errno==ERANGE)
{
perror("something is wrong.");
}