查找字符串中整数的长度

Find the length of an integer within a string

如果我有这样的文本文件:

8f5 

我可以轻松地使用 strstr 来解析其中的值 85。 因此:

//while fgets.. etc (other variables and declarations before it)
char * ptr = strstr(str,"f");
if(ptr != NULL)
{
    int a = atol(ptr-1); // value of 8
    int b = atol(ptr+1); // value of 5
}

但是如果值有两位小数怎么办?我可以 add +2 and -2 参加每个 atol 电话。但是我无法预测值何时小于 10 或更大,例如

12f6

15f15 因为值每次都是随机的(即一位小数或两位)。有没有办法检查字符串之间值的长度,然后使用 atol()?

如果我没看错问题,请使用atol(str)atol(ptr+1)。这将为您提供由 f 分隔的两个数字,无论它们有多长。

如果您不想依赖垃圾字符阻止 atol 解析这一事实,请先设置 *ptr = '[=12=]'

如果文本总是和你发的相似,那么你可以用下面的代码得到字符串的三部分,中间有一个白色的space可以解析另一个token

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

int main(void)
{
    char  string[] = "12f5 1234x2912";
    char *next;

    next = string;
    while (*next != '[=10=]') /* While not at the end of the string */
    {
        char   separator[100];
        size_t counter;
        int    firstNumber;
        int    secondNumber;

        /* Get the first number */
        firstNumber = strtol(next, &next, 10);
        counter     = 0;
        /* Skip all non-numeric characters and store them in `separator' */
        while ((*next != '[=10=]') && (isdigit(*next) == 0))
            separator[counter++] = *next++;
        /* nul terminate `separator' */
        separator[counter] = '[=10=]';
        /* extract the second number */
        secondNumber = strtol(next, &next, 10);
        /* show me how you did it */
        printf("%d:%s:%d\n", firstNumber, separator, secondNumber);
        /* skip any number of white space characters */
        while ((*next != '[=10=]') && (isspace(*next) != 0))
            next++;
    }
}

在上面的示例中,您可以看到正在解析的字符串,您可以阅读 strtol() 手册页以了解此算法为何有效。

通常你不应该使用 atoi()atol() 函数,因为你无法验证输入字符串,因为没有办法知道函数是否成功。