Search code examples
c++parsingarmembeddedgnu

Is there an easy way to parse a float from a string in C++ GNU ARM embedded?


I have this string in my C++ GNU ARM embedded system:

char* TempStr = "pressure 0.85";

I need the number value stored as a separate float variable called presmax.

Up until now the number to be parsed has always been an integer, so I could use sscanf without any issues. However, as I have read about extensively on the web (and experienced first hand), sscanf doesn't typically work on floats in embedded systems (without some extensive configuration/loss of flash space).

I'm wondering if anyone has any suggestions. Perhaps I could parse the "0.85" as a char array? I'm not quite sure how to do that, though it would allow me to use atof() to turn it into a float, as I've done elsewhere in the program.

I realize the other option is to write a function, however I'm quite an amateur programmer so if there's a more robust/time effective solution I'd best take it.

UPDATE: In case it helps, TempStr is a string copied from a .txt file on an SD card using FatFs. Here's the full code that reads two lines and stores the results in TempStr each time. I parse the string into its respective variable each time TempStr is stored:

FILINFO fno;
FIL fsrc;
int FileEnd = 0;
int CurrentLine = 0;
int pressmax = 0;
int timemax = 0;
char* TempStr;
WCHAR CharBuffer[100];

res = f_stat("config.txt", &fno);                               //check for config.txt file
res = f_open(&fsrc, "config.txt", FA_READ | FA_OPEN_ALWAYS);    //open config.txt file

//first line
TempStr = f_gets((char*)CharBuffer, sizeof(fsrc), &fsrc);      
CurrentLine ++;
FileEnd = FileEnd + strlen(TempStr) + 1;

//sscanf(TempStr, "%*s %i", &presmax);       //what I did when presmax was an int

//second line
while ((f_eof(&fsrc) == 0)){                                   
        TempStr = f_gets((char*)CharBuffer, sizeof(fsrc), &fsrc);
        CurrentLine ++;
        FileEnd = FileEnd + strlen(TempStr) + 1;
}

//sscanf(TempStr, "%*s %i", &timemax);     

Using GNU ARM Build tools on an STM32L w/Eclipse.


Solution

  • If you are guaranteed that your input will be in the form of

    text floating_point_number
    

    then once you have TempStr you can advance a pointer through it until you reach the space, and then go one position further to get to the floating point part of the string. Then you pass that pointer to atof to get the value out of the remainder of string. That would look like

    char* fp = TempStr;
    while (*fp != ' ') ++fp; // get to the space
    double value = atof(++fp); // advance to floating point part and pass to atof
    

    If you don't need TempStr after you get the value then you can get rid of fp and just use

    while (*TempStr != ' ') ++TempStr ; // get to the space
    double value = atof(++TempStr); // advance to floating point part and pass to atof