问题
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.
回答1:
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?
回答2:
This should do it
ostringstream myString;
float x;
string s;
if ( x != 0)
myString << x;
myString << " " << s;
return myString.str();
回答3:
ostringstream myString;
float x;
string s;
myString<<x << " " <<s;
return myString.str();
回答4:
or use boost::lexical_cast:
return boost::lexical_cast<string>(x) + " " + s;
回答5:
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
来源:https://stackoverflow.com/questions/15385378/how-can-i-concatenate-float-with-string