user2116010
user2116010

Reputation: 211

How can I concatenate float with string?

I tried this:

ostringstream myString;
float x;
string s;
if(x)
  myString<<x;
else
  myString<<s;
return myString.str();

But it doesn't work. My goal is to concatenate into myString, a float and a string, with a space between them, before testing if one of them is NULL.

Upvotes: 3

Views: 20998

Answers (5)

Ed Barbu
Ed Barbu

Reputation: 1639

C++11 is out. Visual Studio has good support for it, and now has std::to_string(float). After converting to string, just concatenate with the + operator;

string a = "test";
float b = 3.14f;
string result = a + std::to_string(b);

http://en.cppreference.com/w/cpp/string/basic_string/to_string

Also, you might be pleased to now the sto_ family of global functions exist, for converting from string back to a numeral type: http://en.cppreference.com/w/cpp/string/basic_string/stol

Upvotes: 2

c-urchin
c-urchin

Reputation: 4504

or use boost::lexical_cast:

return boost::lexical_cast<string>(x) + " " + s;

Upvotes: 0

bash.d
bash.d

Reputation: 13207

Why the else inbetween? Try this:

ostringstream myString;
float x;
string s;
if (fabsf(x) > 1e-30){
    myString<<x << " ";
}
if(s.length() > 0)
   myString<<s;
return myString.str(); //does ostringstream has a str()-member?

Upvotes: 3

kassak
kassak

Reputation: 4184

ostringstream myString;
float x;
string s;
myString<<x << " " <<s;
return myString.str();

Upvotes: 0

Ed Barbu
Ed Barbu

Reputation: 1639

This should do it

ostringstream myString;
float x;
string s;
if ( x != 0)
  myString << x;
myString << " " << s;
return myString.str();

Upvotes: 0

Related Questions