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

C++如何实现输入文本全大写并生成与文本等长的下划线?

调整方案

你可以通过字符串大写转换+动态生成等长下划线两步实现需求,修改后的代码如下:

#include <string>
#include <iostream>
#include <cctype> // toupper函数依赖的头文件

void DisplayTitle(std::string aTitle) {
    // 1. 将标题全部转为大写
    std::string upperTitle;
    for (unsigned char ch : aTitle) {
        upperTitle += static_cast<char>(std::toupper(ch));
    }
    // 2. 生成和大写标题长度完全一致的下划线
    std::string underline(upperTitle.length(), '-');
    // 输出结果
    std::cout << "\t" << upperTitle << std::endl;
    std::cout << "\t" << underline << "\n\n";
}

注意事项

  • 如果你当前项目已经声明了using namespace std;,可以删除所有std::前缀,代码也可正常运行。
  • 遍历字符时用unsigned char类型是为了避免带符号char出现负值时,传入toupper触发未定义行为,兼容性更好。
  • 下划线使用string的构造函数直接生成指定长度的-字符串,不需要手动调整长度,不管输入的标题有多少字符都能自动适配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 21:15:07