很抱歉这个令人困惑的问题,但我要做的是将数组存储在变量中。
我想将这些数字存储在*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
SOURCE
#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;
}
答案 0 :(得分: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"
中取出数字)。
答案 1 :(得分:-1)
我的版本:
void MyFNatoi(char *numArray, int *value)
{
for (*value = 0; *numArray != '\0'; ++numArray) {
if (0x30 <= *numArray && *numArray <= 0x39) {
*value = 10* *value + *numArray - 0x30;
}
}
}
答案 2 :(得分:-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);
}
}
}