Reputation: 211
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
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
Reputation: 4504
or use boost::lexical_cast:
return boost::lexical_cast<string>(x) + " " + s;
Upvotes: 0
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
Reputation: 4184
ostringstream myString;
float x;
string s;
myString<<x << " " <<s;
return myString.str();
Upvotes: 0
Reputation: 1639
This should do it
ostringstream myString;
float x;
string s;
if ( x != 0)
myString << x;
myString << " " << s;
return myString.str();
Upvotes: 0