0
char msg[40]; 
string s = "The price is $"; 
float price = 120.00; 
string input = " and the tax is $";  
float tax = 5.00;

For example, I want to fill msg with "The price is $120.00 dollars and the tax is $5.00". The code I have so far that is not working is:

msg = s + price + input + tax; 

I am stuck right now and can't figure it out, any help is appreciated. Thanks.

2 Answers 2

3

You should declare msg as a std::string.

Then you can either use stringstream to convert the float to string or with C++11, you can use the function std::to_string(arg) with various supported types for arg.

Sign up to request clarification or add additional context in comments.

Comments

1

You can use the c-function sprintf (unless you want to use a c++ string, in which case stringstream is an easy option.

This can be done by

sprintf(msg, "The price is $%.2f and the tax is $%.2f", price, tax); 

There is a good description of the printf syntax here.

1 Comment

Didn't know this function existed. It is easy to use and got rid of my errors, thanks for the help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.