In C++, toupper() is a library function used to convert a character from lowercase to uppercase. It is defined in the <cctype> (or <ctype.h>) header file.
- Processes a single character based on its ASCII value.
- Leaves uppercase letters, digits, and symbols unchanged.
- Commonly used for character-based transformations in strings.
#include <iostream>
#include <cctype>
using namespace std;
int main(){
char ch = 'g';
cout << "Original Character: " << ch << endl;
cout << "Uppercase Character: " << (char)toupper(ch);
return 0;
}
Output
Original Character: g Uppercase Character: G
Explanation: toupper() converts the lowercase character 'g' into its uppercase equivalent 'G'. The returned ASCII value is typecast to char before printing.
Syntax
toupper(int ch);
Parameter : ch - the character to be converted to uppercase.
Return Value
- Returns uppercase equivalent of the character.
- If input is already uppercase, a digit, or a symbol, it is returned unchanged.
- Returns an integer ASCII value (can be typecast to char).
We can manually typecast it to char using the syntax:
char c = (char) toupper('a');
Examples of toupper()
The following examples illustrates how to use toupper() in various scenarios.
Example: Program to convert a given lowercase alphabet to uppercase in C++.
#include <iostream>
using namespace std;
int main()
{
char c = 'g';
cout << c << " in uppercase is represented as = ";
// toupper() returns an int value there for typecasting
// with char is required
cout << (char)toupper(c);
return 0;
}
Output
g in uppercase is represented as = G
Explanation: 'g' is passed to toupper(), which converts it to 'G', and the result is typecast to char before being displayed.
Example: Program to demonstrates how to convert a given string having lowercase alphabets to uppercase string in C++.
#include <iostream>
using namespace std;
int main()
{
// string to be converted to uppercase
string s = "geeksforgeeks";
for (auto& x : s) {
x = toupper(x);
}
cout << s;
return 0;
}
Output
GEEKSFORGEEKS
Explanation: The loop iterates through each character, toupper() converts lowercase letters to uppercase, and the entire string is transformed into uppercase.
Example: Program to demonstrates the behavior of toupper() when applied to uppercase letters, digits, and special symbols.
#include <iostream>
using namespace std;
int main()
{
string s = "Geeks@123";
for (auto x : s) {
cout << (char)toupper(x);
}
return 0;
}
Output
GEEKS@123
Explanation: Only alphabetic characters are converted to uppercase, while '@', '1', '2', and '3' remain unchanged.