You are here:

C++/Storing strings and variables in a variable

Advertisement


Question
QUESTION: Hi i am trying to store multiple strings and variables in a variable to be returned from a function. Here is the code i have i dont know whats wrong.

output = "\n\n The number of gallons required for the " << vehicle1 << " is " << required1 <<"."
         << "\n The number of gallons required for the " << vehicle2 << " is " << required2 <<"."
         << "\n\n The cost to drive the " << vehicle1 << " per year is " << cost1 << "."
         << "\n The cost to drive the " << vehicle2 << " per year is " << cost2 << "."
         << "\n\n The " << vehicle2 << " will cost $" << difference << " per year less to drive than the " << vehicle1 << ".";

Thanks

ANSWER: John, you don't mention the environment.  In Visual Studio for MFC you can use a CString and the Format and AppendFormat member functions.  Otherwise, the << operator used like you are is for classes which overload the << and >> operator, like the ostream class.

Bill

---------- FOLLOW-UP ----------

QUESTION: Thanks for the reply. im using Visual Studio 2008. im pretty new at c++ so a little more explanation if you dont mind would be great.

thanks

Answer
Ok.

Use an ostringstream.

#include <sstream>

.
.
.

ostringstream output;

output << "\n\n The number of gallons required for the " << vehicle1 << " is " << required1 <<"." << "\n The number of gallons required for the " << vehicle2 << " is " << required2 <<"." << "\n\n The cost to drive the " << vehicle1 << " per year is " << cost1 << "." << "\n The cost to drive the " << vehicle2 << " per year is " << cost2 << "." << "\n\n The " << vehicle2 << " will cost $" << difference << " per year less to drive than the " << vehicle1 << ".";

.
.
.

Now output has the complete output as a string.

cout << output.str();

Bill

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Bill A

Expertise

I can answer questions about C++, programming algorithms, Windows programming in MFC (which is C++). I cannot answer questions about STL (templates) and I have no experience with Linux. I do enjoy reviewing code and critiquing it or finding problems in it. I will also gladly show better algorithms or methods if you want to take advantage of that.

Experience

I've developed a commercial embedded C compiler/assembler and IDE with debugger toolset, of which the IDE and debugger are written in C++. I work in the industry writing high tech embedded programs and Windows programs to communicate with the embedded devices.

Publications
Book: Embedded Systems Design using the Rabbit 3000 Microprocessor Authored Chapter 10 in its entirety.

Education/Credentials
BS Computer Engineering

©2016 About.com. All rights reserved.