在本教程中,我們將借助示例了解 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()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。
