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?
isdigitbefore you usestrtolatoiandstrtolexpect to receive the pointer to the first character of a numeral—your pointer must already be pointing to a digit. Neither “e” nor “d” is a digit when the base is 10. To find the numerals in the string, you should write code to examine each character to determine whether it is a digit or not. Once you have found a digit, you can convert either it (just the one digit) or the sequence of digits (several digits) there to a number, depending on what your need is."e5 d8"tostrtolis not a correct way to find the “5” and convert it to a number.