3

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.

Cartier
  • 429
  • 4
  • 15
user2116010
  • 211
  • 4
  • 7
  • 10

5 Answers5

3

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?
bash.d
  • 13,029
  • 3
  • 29
  • 42
  • i want to check if one of them is NULL – user2116010 Mar 13 '13 at 12:31
  • @user2116010 What do you mean by `NULL`? Equal to `0`? Of length zero? – Peter Wood Mar 13 '13 at 12:32
  • 1
    x can't be `NULL`, at most `0.0f`. And s can't be `NULL`, either as it is on the stack. – bash.d Mar 13 '13 at 12:32
  • `ostringstream` has a [`str`](http://en.cppreference.com/w/cpp/io/basic_stringstream/str) member, returning a `string` which has a `c_str` member. – Peter Wood Mar 13 '13 at 12:34
  • I don't know if it's right but at one point i just make s = NULL and now i want to test if it's null or not – user2116010 Mar 13 '13 at 12:35
  • @user2116010 `s = NULL` will set `s` to be [`empty`](http://en.cppreference.com/w/cpp/string/basic_string/empty), but not NULL. – Peter Wood Mar 13 '13 at 12:39
  • beware, floats should never be compared against absolute value. If that is returned from some operation, it might be almost zero, but non-zero. You might try if (fabsf(x) > 1e-30) instead of if (x). Note that std::string(NULL) will crash, so you have to check NULL before it is passed std::string. Use myString.empty() if does not matter. – Pihhan Mar 13 '13 at 12:48
2

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

Ed Rowlett-Barbu
  • 1,611
  • 10
  • 27
0

This should do it

ostringstream myString;
float x;
string s;
if ( x != 0)
  myString << x;
myString << " " << s;
return myString.str();
Ed Rowlett-Barbu
  • 1,611
  • 10
  • 27
0
ostringstream myString;
float x;
string s;
myString<<x << " " <<s;
return myString.str();
kassak
  • 3,974
  • 1
  • 25
  • 36
0

or use boost::lexical_cast:

return boost::lexical_cast<string>(x) + " " + s;
c-urchin
  • 4,344
  • 6
  • 28
  • 30