CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Mar 2008
    Posts
    17

    Storing floats to a string?

    Is it possible to do this?
    I have tried something like this but it has not worked:
    Code:
    float x = 9;
    float y = 33;
    
    string sum = x;
    sum += "+";
    sum += y;
    I would want the outcome to look like "9+33"

    I know that seems dumb but I am actually trying something on a larger scale.
    I know I could use:
    Code:
    cout << x << "+" << y
    but I need to display this a lot so I would like it to be a string.

    Thanks.

  2. #2
    Join Date
    Nov 2006
    Location
    Australia
    Posts
    1,569

    Re: Storing floats to a string?

    This topic has no doubt been covered already on these forums as well as google, but here is the answer anyway:
    Code:
    #include <string>
    #include <sstream>
    #include <exception>
    
    std::string to_string(int x)
    {
      std::ostringstream o;
    
      if (!(o << x))
        throw std::exception("Couldn't parse integer in to_string.");
    
      return o.str();
    }
    
    int main()
    {
      std::string x = "12 * 12 = " + to_string(12 * 12);
    
      std::cout << x << std::endl;
    
      return 0;
    }
    There is also boost::lexical_cast, but if you are new to C++ it's easier to forget 3rd party libraries until you get more familiar with the language.
    Last edited by Mybowlcut; May 15th, 2008 at 09:51 PM.
    Good judgment is gained from experience. Experience is gained from bad judgment.
    Cosy Little Game | SDL | GM script | VLD | Syntax Hlt | Can you help me with my homework assignment?

  3. #3
    Join Date
    Jan 2003
    Posts
    615

    Re: Storing floats to a string?

    Before post, make an effort yourself, try googling or search here.

    When posting, give a proper description of your problem, include code* and error messages.

    *All code should include code tags

  4. #4
    Join Date
    Mar 2008
    Posts
    17

    Re: Storing floats to a string?

    Thanks. I actually did search Google but for some reason found nothing.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured