Arm Mbed and Pelion Device Management support forum

How to convert string from serial to float?

I’ve tried to recive a valor from the serial input (string) and convert it into a float. There is any function? atof gives me some errores.

I understand that you are using C++ std::string.
atof() takes const char*. You can convert string to const char* using c_str() like this.

double numberInDouble = atof(your_string.c_str());

string::c_str documentation

Ok, that seems to work but i’m having another problem. I’m using “getc()” to catch the serial input string. the Error is: A value of type “int” cannot be used to initialize an entity of type “const char *” in “main.cpp”.

So, you are not using std::string? It would be easier if you post your code.
Why don’t you just put them in a buffer and pass it directly to atof()?

char buf[16];
int buf_index = 0;
//...
buf[buf_index++] = pc.getc();
double numberInDouble = atof(buf);

Hi. Sorry for beeing lost these days, I had some troubles… But I found a easier way to put a float in serial input, I used pc.getc() and introduced “\n” in every number, for example: “120\n” I really don’t know how it works but it actually works haha.