我如何在 C++ 中 return 带有变量和字符的字符串?

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

我有一个字符串函数,我想输出以下 cout 行。

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

问题是函数必须 return 一个字符串,我不确定在这种情况下将这些 cout 语句转换为字符串的最佳方法。

感谢您的帮助。

使用ostringstream,包含<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 的回答可以稍微简化一下。普通的旧字符串可以连接(也可以链接),因此您可以将其减少为:

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"; 
}

哪个效率更高?好吧,这取决于。