如何将C++字符串转换为大写

Tho*_* W. 17 c++ string uppercase

我需要将C++中的字符串转换为完整的大写字母.我一直在寻找一段时间,并找到了一种方法:

#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;
}
Run Code Online (Sandbox Code Playgroud)

不幸的是,这不起作用,我收到此错误消息:

没有匹配函数来调用'transform(std :: basic_string :: iterator,std :: basic_string :: iterator,std :: basic_string :: iterator,

我尝试过其他方法也没用.这是最接近工作的.

所以我要问的是我做错了什么.也许我的语法很糟糕或者我需要包含一些内容.我不确定.

我在这里获得了大部分信息:http: //www.cplusplus.com/forum/beginner/75634/ (最后两篇文章)

lee*_*mes 32

你需要在之前放一个双冒号toupper:

transform(input.begin(), input.end(), input.begin(), ::toupper);
Run Code Online (Sandbox Code Playgroud)

说明:

有两种不同的toupper功能:

  1. toupper在全局命名空间(访问::toupper),来自C.

  2. toupperstd命名空间(访问过std::toupper)中,它具有多个重载,因此不能简单地仅使用名称引用.您必须将其显式地转换为特定的函数签名才能被引用,但获取函数指针的代码看起来很丑:static_cast<int (*)(int)>(&std::toupper)

因为你using namespace std在写作时toupper,隐藏了1.因此根据名称解析规则被选中.

  • @LokiAstari:关键是你想要全局`toupper`,而不是`std::`,这突出了`use namespace std` 的问题——它用你不使用的很多符号污染了默认命名空间不想只得到一两个。如果你只想导入几个符号,你应该只导入那些符号,而不是整个 `std` 命名空间。 (3认同)

yiz*_*lez 6

试试这个小程序,直接来自C++ 参考

#include <iostream>
#include <algorithm> 
#include <string>  
#include <functional>
#include <cctype>

using namespace std;

int main()
{
    string s;
    cin >> s;
    std::transform(s.begin(), s.end(), s.begin(), std::ptr_fun<int, int>(std::toupper));
    cout << s;
    return 0;

}
Run Code Online (Sandbox Code Playgroud)

现场演示

  • std::ptr_fun() 在 c++11 中已弃用,并在 c++14 中删除。 (2认同)

小智 5

提升字符串算法:

#include <boost/algorithm/string.hpp>
#include <string>

std::string str = "Hello World";

boost::to_upper(str);

std::string newstr = boost::to_upper_copy("Hello World");
Run Code Online (Sandbox Code Playgroud)

将C++中的字符串转换为大写字母