How can I concatenate float with string?

一世执手 提交于 2019-12-10 11:08:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!