Get to number from an array and assign to one int

北战南征 提交于 2019-12-25 08:11:27

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!