如何将C ++字符串转换为大写 [英] How to Convert a C++ String to Uppercase
问题描述
我需要将C ++中的字符串转换为完全大写.我搜索了一段时间,发现了一种解决方法:
I need to convert a string in C++ to full upper case. I've been searching for a while and found one way to do it:
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main()
{
string input;
cin >> input;
transform(input.begin(), input.end(), input.begin(), toupper);
cout << input;
return 0;
}
不幸的是,这不起作用,我收到了以下错误消息:
Unfortunately this did not work and I received this error message:
没有匹配函数可调用'transform(std :: basic_string :: iterator,std :: basic_string :: iterator,std :: basic_string :: iterator,
no matching function for call to 'transform(std::basic_string::iterator, std::basic_string::iterator, std::basic_string::iterator,
我尝试了其他同样行不通的方法.这是最接近工作的地方.
I've tried other methods that also did not work. This was the closest to working.
所以我要问的是我做错了什么.也许我的语法不好,或者我需要添加一些内容.我不确定.
So what I'm asking is what I am doing wrong. Maybe my syntax is bad or I need to include something. I am not sure.
我在这里获得了大部分信息: http://www.cplusplus.com/forum/beginner/75634/(最后两个帖子)
I got most of my info here: http://www.cplusplus.com/forum/beginner/75634/ (last two posts)
推荐答案
您需要在 toupper
之前加一个双冒号:
You need to put a double colon before toupper
:
transform(input.begin(), input.end(), input.begin(), ::toupper);
说明:
有两种不同的 toupper
函数:
toupper
(通过 :: toupper
访问). std
名称空间中的
toupper
(通过 std :: toupper
访问)具有多个重载,因此不能简单地引用仅带有名称.您必须将其显式转换为特定的函数签名才能被引用,但是获取函数指针的代码看起来很丑: static_cast< int(*)(int)>(& std :: toupper)
toupper
in the std
namespace (accessed with std::toupper
) which has multiple overloads and thus cannot be simply referenced with a name only. You have to explicitly cast it to a specific function signature in order to be referenced, but the code for getting a function pointer looks ugly: static_cast<int (*)(int)>(&std::toupper)
由于您正在使用命名空间std
,因此在编写 toupper
时,2.隐藏1.并根据名称解析规则进行选择.
Since you're using namespace std
, when writing toupper
, 2. hides 1. and is thus chosen, according to name resolution rules.
这篇关于如何将C ++字符串转换为大写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!