2

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

3
  • Shorter version would be std::istringstream{std::string{"0.5"}} >> value ; Commented Jun 13, 2013 at 14:19
  • @0x499602D2: Even shorter: std::istringstream{"0.5"} >> value; Commented Jun 13, 2013 at 14:21
  • @AndyProwl lol that too Commented Jun 13, 2013 at 14:21

1 Answer 1

5

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...
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.