Reputation: 9634
I've been trying to convert a simple string to a float, but I'm having no luck with it. this is what I've got at the moment:
int main()
{
float value;
std::string stringNum = "0.5";
std::istringstream(stringNum) >> value;
return 0
}
but I'm getting this error:
Error 2 error C2440: '<function-style-cast>' : cannot convert from 'std::string' to 'std::istringstream' c:\users\administrator\desktop\Test\main.cpp 12
can anyone give me some guidance here on how to just simply convert the string to a float?
Thanks
Upvotes: 2
Views: 444
Reputation: 126452
Most likely you haven't included all the relevant headers:
#include <string>
#include <sstream>
Here is a live example showing that your code compiles when the appropriate headers are included.
In general, you should not rely on indirect inclusion of a necessary standard header file from another standard header file (unless, of course, this inclusion is documented in the Standard itself).
Also notice, that you are creating a temporary string stream, which will be destroyed at then end of the evaluation of the expression
std::istringstream(stringNum) >> value
You may want to create a stream object this way instead:
std::istringstream ss(stringNum);
ss >> value;
// Here you can use ss again...
Upvotes: 5