C++ toupper()

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

示例

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

int main() {

// convert 'a' to uppercase char ch = toupper('a');
cout << ch; return 0; } // Output: 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 = 'A',所以toupper()返回相同的值。
  • 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 << "The uppercase version of \"" << str << "\" is " << endl;

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

// convert str[i] to uppercase ch = toupper(str[i]);
cout << ch; } return 0; }

输出

The uppercase version of "John is from USA." is 
JOHN IS FROM USA.

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

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

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

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

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

ch = toupper(str[i]);

然后我们在循环中打印ch。到循环结束时,整个字符串已转换为大写并打印出来。


另请阅读

在我们结束之前,让我们来测试一下你对 C++ cctype toupper() 的知识!你能解决下面的挑战吗?

挑战

编写一个函数,将句子转换为苏格兰式的尖叫。

  • 将给定的字符串str转换为苏格兰式的尖叫,即将所有字符转换为大写,并返回转换后的字符串。
  • 例如,如果字符串是str = "Hello World!",则输出应为"HELLO WORLD!"
你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战