I'm working on an assignment and as part of it I need to extract the integer from a string.
I've tried using the atoi()
function, but it always returns a 0
, so then I switched up to strtol()
, but it still returns a 0
.
The goal is to extract the integers from the string and pass them as arguments to a different function. I'm using a function that then uses these values to update some data (update_stats
).
Please keep in mind that I'm fairly new to programming in the C language, but this was my attempt:
void get_number (char str[]) {
char *end;
int num;
num = strtol(str, &end, 10);
update_stats(num);
num = strtol(end, &end, 10);
update_stats(num);
}
The purpose of this is in a string "e5 d8"
(for example) I would extract the 5
and the 8
from that string.
The format of the string is always the same.
How can I do this?
strtol
doesn't find a number in a string. It converts the number at the beginning of the string. (It does skip whitespace, but nothing else.)
If you need to find where a number starts, you can use something like:
const char* nump = strpbrk(str, "0123456789");
if (nump == NULL) /* No number, handle error*/
If your numbers might be signed, you'll need something a bit more sophisticated. One way is to do the above and then back up one character if the previous character is -
. But watch out for the beginning of the string:
if ( nump != str && nump[-1] == '-') --nump;
Just putting -
into the strpbrk
argument would produce false matches on input like non-numeric7
.