我在使用 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 char
或 EOF
的期望值,因此在传递它们之前,您应该将 char
参数转换为 unsigned char
。
关于c++ - 使用 toupper() 函数连接时无法打印字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68882657/