0

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.

1

2 Answers 2

6

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();
}
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.