Search code examples
cstringtokenize

Split float from beginning of string in C


I'm currently writing a program in C, that can tokenize an arithmetic expression, but I've only provided a minimum, reproducible example here.

The following code successfully splits -5.2foo into -5.2 and foo:

#include <stdio.h>

int main(void)
{
    char str[] = "-5.2foo";
    float f;
    sscanf(str, "%f%s", &f, str);
    printf("%f | %s\n", f, str);
    return 0;
}

But if the string only contains a floating point number (e.g. -5.2), the program will print -5.2 | -5.2, so the string doesn't seem to be empty. Is there a way to split a float from a string in C and then store the remaining string?


Solution

  • You can use the strtof() function, which has an argument to (optionally) return a pointer to the 'rest' of the input string (after the float has been extracted):

    #include <stdio.h>
    #include <stdlib.h>
    
    int main(void)
    {
        char str[] = "-5.2foo";
        char* rest;
        float f;
        f = strtof(str, &rest);
        printf("%f | %s\n", f, rest);
        // And, if there's nothing left, then nothing will be printed ...
        char str2[] = "-5.2";
        f = strtof(str2, &rest);
        printf("%f | %s\n", f, rest);
        return 0;
    }
    

    From the cppreference page linked above (str_end is the second argument):

    The functions sets the pointer pointed to by str_end to point to the character past the last character interpreted. If str_end is a null pointer, it is ignored.

    If there is nothing 'left' in the input string, then the returned value will point to that string's terminating nul character.