将字符值转换为整数值

时间:2011-10-18 06:39:43

标签: c

在这里,当我发现'h'我必须访问p和h之间的值,即123,我希望它有int并将其存储在值123本身我怎么能这样做任何人告诉我逻辑,我写的代码不起作用,以及当指针增加时如何复制值

    main()
        {
            char *ptr1 = "p123h12";
            int value;
            while(*ptr1!= '\0')
            {
                if(*ptr1 == 'h')
                {
                value = (int)atoi(ptr1);
                printf("%d\n", value);
                }
            ptr1++;
            }

        }

2 个答案:

答案 0 :(得分:1)

使用sscanf

int value;
sscanf (ptr1,"p%dh12",&value);

<强>更新

int i,j;
int values[MAX_VALUES];
int startIdx = -1;
char *ptr1 = "p123hxxxxp124hxxxxp123145hxxxx";
char buffer[16];
for(i=0,j=0; i<strlen(ptr1);i++)
{
    if(startIdx>=0 && ptr[i] == 'h')
    {
        strncpy(buffer,ptr1+startIdx,i-startIdx+1);
        buffer[i-startIdx+1]='\0';
        sscanf (buffer,"p%dh",&(values[j++]));
        startIdx = -1;
    }
    else if(ptr[i] == 'p')
    {
        startIdx = i;
    }
}    

答案 1 :(得分:0)

这是一个很好的起点:

#include <stdio.h>
#include <ctype.h>

int main (void) {
    char *p, *str = "p123h12p97h62p32h";
    int accum = 0;

    // Process every character.

    for (p = str; *p != '\0'; p++) {
        // 'p' resets the accumulator.
        // 'h' outputs the accumulator.
        // Any digit adjusts the accumulator.

        if (*p == 'p')       accum = 0;
        if (*p == 'h')       printf ("Processing %d\n", accum);
        if (isdigit (*p))    accum = accum * 10 + *p - '0';
    }

    return 0;
}

如果您的输入字符串符合指定的格式,则可以正常工作,输出:

Processing 123
Processing 97
Processing 32

如果您的输入字符串可能形成不当,则需要添加一些防御性编码。