跳到主要内容

C++ toupper() 将字符转换为大写

C++ 中的 toupper() 函数用于将给定字符转换为大写。它定义在 cctype 头文件中。

示例

#include <iostream>
#include <cctype>
using namespace std;

int main() {

// 将 'a' 转换为大写
char ch = toupper('a');

cout << ch;

return 0;
}

// 输出:A

toupper() 语法

toupper() 函数的语法是:

toupper(int ch);

toupper() 参数

toupper() 函数接受以下参数:

  • ch - 一个字符,转换为 int 类型或 EOF

toupper() 返回值

toupper() 函数返回:

  • 对于字母 - ch 的大写版本的 ASCII 码
  • 对于非字母 - ch 的 ASCII 码

toupper() 原型

cctype 头文件中定义的 toupper() 函数原型是:

int toupper(int ch);

可以看到,字符参数 ch 被转换为 int,即其 ASCII 码。

由于返回类型也是 inttoupper() 返回转换后字符的 ASCII 码。

toupper() 未定义行为

toupper() 的行为在以下情况下是未定义的

  • ch 的值无法表示为 unsigned char,或
  • ch 的值不等于 EOF

示例 1:C++ toupper()

#include <cctype>
#include <iostream>
using namespace std;

int main() {
char c1 = 'a', c2 = 'b', c3 = '9';

cout << (char) toupper(c1) << endl;
cout << (char) toupper(c2) << endl;
cout << (char) toupper(c3);

return 0;
}

输出

A
B
9

这里,我们使用 toupper() 将字符 c1c2c3 转换为大写。

注意打印输出的代码:

cout << (char) toupper(c1) << endl;

这里,我们使用代码 (char) toupper(c1)toupper(c1) 的返回值转换为 char

还要注意,最初:

  • c2 = 'b',因此 toupper() 返回 B
  • c3 = '9',因此 toupper() 返回相同的值

示例 2:C++ toupper() 无类型转换

#include <cctype>
#include <iostream>
using namespace std;

int main() {
char c1 = 'A', c2 = 'b', c3 = '9';

cout << toupper(c1) << endl;
cout << toupper(c2) << endl;
cout << toupper(c3);

return 0;
}

输出

65
66
57

这里,我们使用 toupper() 将字符 c1c2c3 转换为大写。

然而,我们没有将 toupper() 返回的值转换为 char 类型。因此,这个程序打印了转换后字符的 ASCII 值,分别是:

  • 65 - 'A' 的 ASCII 码
  • 66 - 'B' 的 ASCII 码
  • 57 - '9' 的 ASCII 码

示例 3:C++ toupper() 用于字符串

#include <cctype>
#include <iostream>
#include <cstring>
using namespace std;

int main() {
char str[] = "John is from USA.";
char ch;

cout << "字符串 \"" << str << "\" 的大写版本是 " << endl;

for (int i = 0; i < strlen(str); i++) {

// 将 str[i] 转换为大写
ch = toupper(str[i]);

cout << ch;
}

return 0;
}

输出

字符串 "John is from USA." 的大写版本是
JOHN IS FROM USA.

这里,我们创建了一个 C 字符串 str,值为 "John is from USA."

然后,我们使用 for 循环将 str 的所有字符转换为大写。循环从 i = 0 运行到 i = strlen(str) - 1

for (int i = 0; i < strlen(str); i++) {
...
}

换句话说,循环遍历整个字符串,因为 strlen() 返回 str 的长度。

在每次循环的迭代中,我们将字符串元素 str[i](字符串的单个字符)转换为大写,并将其存储在 char 变量 ch 中。

ch = toupper(str[i]);

我们在循环内部打印 ch。循环结束时,整个字符串都已以大写形式打印出来。