atof question

Hi there!

Can anyone tell me why this compile works...

float SP = atof("12.34");
Serial.print(SP);

while this doesn't work....

String messageTemp;
...
float SP = atof(messageTemp);
Serial.print(SP);

Compiler says: cannot convert 'String' to 'const char*' for argument '1' to 'double atof(const char*)'

SP is declared as float, not const char...

Thankful for any help.

Well, the compiler tells you that it can't convert the first argument to const char*. SP is not an argument.
You simply can't pass a String object to atof, if you really want to use String, then pass in the underlying c-string:

float SP = atof(messageTemp.c_str());

It doesnt work because functions from ato... group expect a pointer to a C-string as input. AString` object does not satisfy that requirement.

A String object is not implicitly convertible to a C-string pointer (which is what the compiler is telling you), but you can obtain such pointer explicitly by calling c_str() method of your String object.

Just remember that the C-string pointer it returns does not point to a "stable" C-string. Any modifying operations that you apply to the original String will affect/damage the C-string. Don't store the pointer returned by c_str() for long-term use.

This works fine! Many thanks! And thanks for the explanation as well!