c++ - 使用 toupper() 函数连接时无法打印字符串

标签 c++ c++14

我在使用 toupper() 函数时遇到问题:
代码:

#include <iostream>
#include <string>
using namespace std;
int main (){
    string input {"ab"};
    string output {""};
    cout << output + toupper(input[0]);
    return 0;
}

错误是:
没有运算符“+”匹配这些操作数——操作数类型是:std::_cx11::string + int。
但如果我写:

#include <iostream>
#include <string>
using namespace std;
int main (){
    string input {"ab"};
    string output {""};
    char temp = toupper(input[0]);
    cout << output + temp;
    return 0;
}

它工作正常。谁能告诉我为什么?

最佳答案

toupper的返回值是一个 int,你不能添加一个 std::string 和一个 int,因为不存在 运算符+(整数)。您的 char temp 在其初始化期间将 int 返回值隐式转换为 char,并且由于 std::string 具有operator+(char) 重载,这有效。尽管您可以使用 static_cast 复制相同的行为:

cout << output + static_cast<char>(toupper(input[0]));

作为旁注,ctype 通常会传递一个可表示为 unsigned charEOF 的期望值,因此在传递它们之前,您应该将 char 参数转换为 unsigned char

关于c++ - 使用 toupper() 函数连接时无法打印字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68882657/

相关文章:

c++ - 如何在 QTableWidget 中获取多个选定行的索引

c++ - 什么是模板<typename T, T t> 习语?

c++ - 将 sigwait 与 std::thread 和管道一起使用

c++ - 尝试理解编译器错误信息 : default member initializer required before the end of its enclosing class

c++ - 带有 uint8_t 的 reinterpret_cast 是否违反了严格别名规则?

c++ - 在 C++ 中,new 运算符之后和类型之前的括号 (placement_params) 是什么意思?

c++ - Boost 程序选项允许输入值集

c++ - C++上数组错误的大小

c++ - 传递大小限制为可扩展大小集的 std::array 参数

c++ - 映射变得非常大后,Linux C++ 程序因 St9bad_alloc 而崩溃