0

抱歉这个令人困惑的问题,但我想做的是将数组存储在变量中。

我想将数字存储在*value其中,而int value: -12118433669不是int value: 123456789.

输出

123456789
array: '123456789' int value: -1218433669
0001234
array: '0001234' int value: -1218433669
5
array: 'abc5xyz' int value: -1218433669

array: '' int value: -1218433669
987654321
array: '987654321' int value: -1218433669

来源

#include <stdio.h>

MyFNatoi(char *numArray, int *value) {

    int i;

    for (i = 0; i < 10; i++) {
        if (numArray[i] > 47 && numArray[i] < 58) {
            printf("%c", numArray[i] - 0);
        }
    }

}

int main() {

    char numbers[5][10] = { "123456789", "0001234", "abc5xyz", "", "987654321" };
    int i, value;

    for(i = 0; i < 5; i++) {
        MyFNatoi(numbers[i], &value);
        printf("\narray: '%s' int value: %d\n", numbers[i], value);
    }
    return 0;

}
4

3 回答 3

0

我提出这个功能:

void MyFNatoi(const char *str, int *value)
{
    if (value == NULL)
        return;

    *value = 0;

    if (str != NULL)
    {
        int negative = 0;

        if (*str == '-')
        {
            negative = 1;
            str++;
        }

        while (*str && isdigit(*str))
        {
            *value = (*value * 10) + (*str++ - '0');
        }

        if (negative)
            *value *= -1;
    }
}

它处理负数,并且只检查前导数字("abc123def456"例如,不会从中提取数字)。

于 2012-04-05T05:54:27.453 回答
-1

我的版本:

void MyFNatoi(char *numArray, int *value)
{
    for (*value = 0; *numArray != '\0'; ++numArray) {
        if (0x30 <= *numArray && *numArray <= 0x39) {
            *value = 10* *value + *numArray - 0x30;
        }
    }
}
于 2012-04-05T00:55:28.423 回答
-1
#define Zero '0'
#define Nine '9'

void MyFNatoi(char *numArray, int *value) {

    int i;
    *value = 0;
    for (i = 0; i < 10 && numArray[i] != 0; i++) {
        if (numArray[i] >= Zero && numArray[i] <= Nine) {
            *value = *value * 10 + (numArray[i] - Zero);
        }
    }

}
于 2012-04-05T10:14:11.453 回答