使用 toupper() 函数连接时无法打印字符串
unable to print string while concatenation using toupper() function
我在使用 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
的 return 值是一个 int
,您不能添加 std::string
和 int
,因为不存在 operator+(int)
。您的 char temp
在其初始化期间将 int
return 值隐式转换为 char
,并且由于 std::string
具有 operator+(char)
重载,因此这有效。尽管您可以使用 static_cast
来复制相同的行为:
cout << output + static_cast<char>(toupper(input[0]));
作为旁注,ctype
通常会传递一个可表示为 unsigned char
或 EOF
的期望值,因此您应该转换 char
unsigned char
传递参数之前。
我在使用 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
的 return 值是一个 int
,您不能添加 std::string
和 int
,因为不存在 operator+(int)
。您的 char temp
在其初始化期间将 int
return 值隐式转换为 char
,并且由于 std::string
具有 operator+(char)
重载,因此这有效。尽管您可以使用 static_cast
来复制相同的行为:
cout << output + static_cast<char>(toupper(input[0]));
作为旁注,ctype
通常会传递一个可表示为 unsigned char
或 EOF
的期望值,因此您应该转换 char
unsigned char
传递参数之前。