Home > Net >  How do I return a string with variables and characters in c ?
How do I return a string with variables and characters in c ?

Time:05-19

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.

CodePudding user response:

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();
}

CodePudding user response:

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.

  • Related