在本教程中,我们将借助示例了解 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(int ch);
参数:
toupper() 函数采用以下参数:
- ch- 一个角色,投射到
int输入或EOF
返回:
toupper() 函数返回:
- 对于字母- 大写版本的 ASCII 码
ch - 对于非字母- 的 ASCII 码
ch
toupper() 原型
cctype头文件中定义的toupper()的函数原型为:
int toupper(int ch);
正如我们所看到的,字符参数ch被转换为int,即它的ASCII码。
由于返回类型也是int , toupper(),所以返回转换后字符的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() 将字符 c1 , c2 和 c3 转换为大写。
注意打印输出的代码:
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() 将字符 c1 , c2 和 c3 转换为大写。
但是,我们还没有将 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.
在这里,我们创建了一个 C-string 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。在循环结束时,整个字符串都以大写形式打印。
相关用法
- C++ towupper()用法及代码示例
- C++ towlower()用法及代码示例
- C++ towctrans()用法及代码示例
- C++ tolower()用法及代码示例
- C++ complex tanh()用法及代码示例
- C++ type_info name用法及代码示例
- C++ tellg()用法及代码示例
- C++ type_info before用法及代码示例
- C++ tgamma()用法及代码示例
- C++ complex tan()用法及代码示例
- C++ trunc()用法及代码示例
- C++ time()用法及代码示例
- C++ typeinfo::bad_cast用法及代码示例
- C++ typeinfo::bad_typeid用法及代码示例
- C++ tanh()用法及代码示例
- C++ tan()用法及代码示例
- C++ tmpnam()用法及代码示例
- C++ type_traits::is_null_pointer用法及代码示例
- C++ tmpfile()用法及代码示例
- C++ transform_inclusive_scan()用法及代码示例
注:本文由纯净天空筛选整理自 C++ toupper()。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。
