Namespaces
Variants

std:: toupper

From cppreference.net
定义于头文件 <cctype>
int toupper ( int ch ) ;

根据当前安装的C语言区域设置定义的字符转换规则,将给定字符转换为大写形式。

在默认的 "C" 区域设置中,以下小写字母 abcdefghijklmnopqrstuvwxyz 会被替换为对应的大写字母 ABCDEFGHIJKLMNOPQRSTUVWXYZ

目录

参数

ch - 待转换的字符。若 ch 的值无法表示为 unsigned char 且不等于 EOF ,则行为未定义。

返回值

转换后的字符,若当前 C 本地环境未定义大写版本则返回 ch

注释

<cctype> 中的所有其他函数一样,如果参数值既不能表示为 unsigned char 也不等于 EOF ,则 std::toupper 的行为是未定义的。要安全地使用这些函数处理普通 char (或 signed char ),应首先将参数转换为 unsigned char

char my_toupper(char ch)
{
    return static_cast<char>(std::toupper(static_cast<unsigned char>(ch)));
}

同样地,当迭代器的值类型为 char signed char 时,不应直接将其与标准算法一起使用。而应先将值转换为 unsigned char

std::string str_toupper(std::string s)
{
    std::transform(s.begin(), s.end(), s.begin(),
                // static_cast<int(*)(int)>(std::toupper)         // 错误
                // [](int c){ return std::toupper(c); }           // 错误
                // [](char c){ return std::toupper(c); }          // 错误
                   [](unsigned char c){ return std::toupper(c); } // 正确
                  );
    return s;
}

示例

#include <cctype>
#include <climits>
#include <clocale>
#include <iostream>
#include <ranges>
int main()
{
    for (auto bd{0}; unsigned char lc : std::views::iota(0, UCHAR_MAX))
        if (unsigned char uc = std::toupper(lc); uc != lc)
            std::cout << lc << uc << (13 == ++bd ? '\n' : ' ');
    std::cout << "\n\n";
    unsigned char c = '\xb8'; // ISO-8859-15 中的字符 ž
                              // 但在 ISO-8859-1 中是 ¸ (软音符)
    std::setlocale(LC_ALL, "en_US.iso88591");
    std::cout << std::hex << std::showbase;
    std::cout << "在 iso8859-1 中,toupper('0xb8') 返回 " << std::toupper(c) << '\n';
    std::setlocale(LC_ALL, "en_US.iso885915");
    std::cout << "在 iso8859-15 中,toupper('0xb8') 返回 " << std::toupper(c) << '\n';
}

输出:

aA bB cC dD eE fF gG hH iI jJ kK lL mM
nN oO pP qQ rR sS tT uU vV wW xX yY zZ
in iso8859-1, toupper('0xb8') gives 0xb8
in iso8859-15, toupper('0xb8') gives 0xb4

参见

将字符转换为小写
(函数)
使用 locale 的 ctype 平面将字符转换为大写
(函数模板)
将宽字符转换为大写
(函数)
C 文档 for toupper

外部链接

1. ISO/IEC 8859-1 . 来自维基百科。
2. ISO/IEC 8859-15 . 来自维基百科。