我如何返回C++中的变量和字符的字符串?

发布于 2025-01-30 16:48:50 字数 390 浏览 4 评论 0原文

我有一个字符串功能,我想输出以下代表行。

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

问题是该功能必须返回字符串,我不确定在这种情况下将这些Cout语句转换为字符串的最佳方法。

谢谢您的任何帮助。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

南街女流氓 2025-02-06 16:48:50

使用OSTRINGSTREAM,包括&lt; sstream&gt;

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

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();
}
狼性发作 2025-02-06 16:48:50

德里克的答案可以简化一些。可以将普通的旧字符串连接(也可以链接),因此您可以将其降低到:

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

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

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文