问题
I'm working on my homework and trying to get two characters which are numbers from an array for example ABC10DEF
I want to get 10
and store it in an int
type.
number_holder_1 = back[3] - '0';
number_holder_2 = back[4] - '0';
number = number_holder_1 * 10 + number_holder_2;
This doesn't work I don't know why.
When I print out the value of number_holder_1
it does display 1
and when I display number_holder_2
it display 0
but when I print number
it just display 0
I don't know how.
UPDATE:
The number
, number_holder_1
and number_holder_2
are define as int
type.
the array called back
that holding ABC10DEF
is passing from the main.
回答1:
It appears to be an implementation mistake, because using what you have given, with some better variable names, it does work.
#include <stdio.h>
#include <ctype.h>
int letter2int(char c) {
int n;
if (isdigit(c)) {
n = c - '0';
} else {
n = -1; /* error */
}
/* for debugging */
printf("For character '%c' we get number '%d'.\n", c, n);
return n;
}
int main(int argc, char** argv) {
const char str[] = "ABC10DEF";
int tens, ones;
int result;
tens = letter2int(str[3]);
ones = letter2int(str[4]);
result = tens * 10 + ones;
printf("Result: %d\n", result);
return 0;
}
This can be generalized to either form a atoi function (ASCII to integer) or extract the first number that occurs in a string (terminated by any non-digit character) by using a loop and a char
pointer to index over the string str
.
Using i
as the zero-based index, result += number * (int)pow(10, i);
.
来源:https://stackoverflow.com/questions/10640288/get-to-number-from-an-array-and-assign-to-one-int