【问题标题】:unable to print string while concatenation using toupper() function使用 toupper() 函数连接时无法打印字符串
【发布时间】:2023-03-27 13:00:02
【问题描述】:

我在使用 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,而不是 char (int toupper( int ch ); ),string + int 是不可能的。
  • toupper 返回int,而不是charoperator +std::stringint 没有过载,但 std::stringchar 有一个过载。见here

标签: c++ c++14


【解决方案1】:

toupper 的返回值为int,由于不存在operator+(int),因此您无法添加std::stringint。您的 char temp 在初始化期间将 int 返回值隐式转换为 char,并且由于 std::string 具有 operator+(char) 重载,因此可以正常工作。虽然您可以使用 static_cast 来复制相同的行为:

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

附带说明,ctype 函数通常是一个期望值,可以表示为 unsigned charEOF,以便传递,因此您应该在传递之前将 char 参数转换为 unsigned char

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-30
    • 1970-01-01
    • 2015-11-16
    • 1970-01-01
    相关资源
    最近更新 更多