lundi 18 juin 2018

How to handle empty string to float conversion in C++?

I have a vector of strings receiving from a socket connection. Those strings I like to map to different variables. As I need the float values for some calculations, I made the following function:

float MyExample::stringToFloat(std::string strToConvert)
{
    // If the input string is empty or not a number an exception is thrown. 
    //As an empty string means no data available it returns 0.0
    try
    {
        return std::stof(strToConvert);
    }
    catch (std::exception& exception)
    {
        return 0.0;
    }
}

When I call the function multiple times with empty strings the program crashes. My Qt Creator reports The program has unexpectedly finished. The process was ended forcefully. Is there a cleaner more elegant way for such a function?

Aucun commentaire:

Enregistrer un commentaire