Okay so this is getting on my nerves now. Say I have a string like this
"The average value for box 1 is:" and I have a float variable containing digits. How do i make the final result like this:
"The average value for box 1 is: 12.01" ?? In Java we use
"The average value for box 1 is:" + avg1

According to cout usage and stuff it should be.
"The average value for box 1 is:" << avg 1. But that doesnt work :)

Any help appreciated.
Thanks!

Note: Im planning on using this with a Message box.

Recommended Answers

All 4 Replies

"It doesn't work." That's the best description of the error you can give?

Without code nor a description of what it does wrong, there's not much to say. Based on what you've posted it's because you didn't actually use cout << "The average value for box 1 is:" << avg1

>>Note: Im planning on using this with a Message box

If so then you will need to convert the variable to a string if its not already. A handy tool is to use something like the following :

template<typename ReturnType, typename InputType>
ReturnType convertTo(const InputType& input){
 std::stringstream stream; //#include <sstream> for this
 ReturnType var = ReturnType();
 if(! (stream << input && stream >> var ) ) throw std::exception("Conversion failed");

 return var;
}
//...
//use like this
float f = 3.14f;
string str = "PI = " + convertTo<string>(f);

@WaltP ... No, but I thought you could understand right off the bat why it wouldnt work.

and, I figured it out by myself. I used strcopy and strcat to join the two.

I used strcopy and strcat to join the two.

As firstPerson said, you could use a std::stringstream for this:

/* A string and a double that we want to combine */
std::string messageRoot("The average value for box 1 is: ");
double ave = 12.01;

/* Make a stringstream (initialised with the string) to combine them in */
std::stringstream sstr(messageRoot);

/* Add the double to the end */
sstr << ave;

/* Convert the string stream back to a normal string */
std::string outputMessage(sstr.str());

This is basically the same code, but not wrapped up in a nice function (in case you find the template stuff intimidating) :)

you can read more about std::stringstream here

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.