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.

Flann3l
  • 69
  • 5
  • Does this answer your question? [How to concatenate two strings in C++?](https://stackoverflow.com/questions/15319859/how-to-concatenate-two-strings-in-c) – Iłya Bursov May 18 '22 at 22:32

2 Answers2

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();
}
Derek T. Jones
  • 1,800
  • 10
  • 18
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.

Paul Sanders
  • 24,133
  • 4
  • 26
  • 48