You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改C++控制台消息框函数使其支持传入自定义文本参数

修改方案

只需要调整Msg_Box函数的参数定义,替换内部硬编码的消息内容即可,具体修改如下:

1. 核心修改点

  • 给Msg_Box新增const std::string&类型的形参,接收传入的自定义文本
  • 删除函数内部原来硬编码的std::string message = "To be, or not to be...";行,直接使用形参作为消息内容
  • 可选:可以给形参加默认值,不传内容的时候也能兼容原有调用逻辑

2. 修改后完整代码

#include <iostream>
#include <string>

// 形参加默认值,支持有参数/无参数两种调用方式
void Msg_Box(const std::string& message = "To be, or not to be...")
{
    // Box edges and corners (all double thick line)
    // T for top, B for bottom, L for left, R for right
    const char TB = '\xCD'; // 205
    const char LR = '\xBA'; // 186
    const char TL = '\xC9'; // 201
    const char TR = '\xBB'; // 187
    const char BL = '\xC8'; // 200
    const char BR = '\xBC'; // 188

    std::string margin = "  ";
    std::string line(message.length() + 2 * margin.length(), TB);

    std::cout << TL << line << TR << std::endl;
    std::cout << LR << margin << message << margin << LR << std::endl;
    std::cout << BL << line << BR << std::endl;
    std::cout << std::endl;
    
}

int main()
{
    // 自定义文本调用
    Msg_Box("自定义文本内容");
    // 也可以不传参数使用默认内容
    Msg_Box();
    return 0;
}

3. 调用说明

  • 直接传入字符串常量即可:Msg_Box("你要显示的任意内容");
  • 也可以传入std::string类型的变量:
    std::string my_msg = "测试消息";
    Msg_Box(my_msg);
    
  • 如果不需要兼容无参数调用,去掉形参的默认值即可。

内容的提问来源于stack exchange,提问作者Alex Pina

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 09:09:00