Flann3l
Flann3l

Reputation: 69

How do I return a string with variables and characters in c++?

I have a string function that I would like to output the following cout lines.

 string print_ticket(void){
        if(sold_status == true){
            cout<<seat_number<<" "<<seat_number<<"sold";
        }
        else{
            cout<<seat_number<<" "<<seat_number<<"available";
        }
    }

The problem is the function must return a string and I'm not sure the best way to turn these cout statement into a string in this scenario.

Thank you for any assistance.

Upvotes: 0

Views: 288

Answers (2)

catnip
catnip

Reputation: 25388

Derek's answer can be simplified somewhat. Plain old strings can be concatenated (and also chained), so you can reduce it to:

string print_ticket(void){
    string seat_number_twice = seat_number + " " + seat_number + " ";  // seems a bit weird, but hey
    if (sold_status)
        return seat_number_twice + "sold"; 
    return seat_number_twice + "available"; 
}

Which is more efficient? Well, it depends.

Upvotes: 1

Derek T. Jones
Derek T. Jones

Reputation: 1812

Use ostringstream, available when including <sstream>:

string print_ticket(void){
    std::ostringstream sout;
    if (sold_status) {
        sout << seat_number << " " << seat_number << "sold";
    }
    else {
        sout << seat_number << " " << seat_number << "available";
    }
    return sout.str();
}

Upvotes: 6

Related Questions