The toupper() function in C++ converts a given character to uppercase. It is defined in the cctype header file.
Example
toupper() Syntax
The syntax of the toupper() function is:
toupper(int ch);
toupper() Parameters
The toupper() function takes the following parameter:
- ch - a character, casted to
inttype orEOF
toupper() Return Value
The toupper() function returns:
- For Alphabets - the ASCII code of the uppercase version of ch
- For Non-Alphabets - the ASCII code of ch
toupper() Prototype
The function prototype of toupper() as defined in the cctype header file is:
int toupper(int ch);
As we can see, the character argument ch is converted to int i.e. its ASCII code.
Since the return type is also int, toupper() returns the ASCII code of the converted character.
toupper() Undefined Behavior
The behaviour of toupper() is undefined if:
- the value of ch is not representable as
unsigned char, or - the value of ch is not equal to
EOF.
Example 1: C++ toupper()
Output
A B 9
Here, we have converted the characters c1, c2, and c3 to uppercase using toupper().
Notice the code for printing the output:
cout << (char) toupper(c1) << endl;
Here, we have converted the return value of toupper(c1) to char using the code (char) toupper(c1).
Also notice that initially:
c2 = 'A', sotoupper()returns the same valuec3 = '9', sotoupper()returns the same value
Example 2: C++ toupper() without Type Conversion
Output
65 66 57
Here, we have converted the characters c1, c2, and c3 to uppercase using toupper().
However, we have not converted the returned values of toupper() to char. So, this program prints the ASCII values of the converted characters, which are:
65- the ASCII code of'A'66- the ASCII code of'B'57- the ASCII code of'9'
Example 3: C++ toupper() with String
Output
The uppercase version of "John is from USA." is JOHN IS FROM USA.
Here, we have created a C-string str with the value "John is from USA.".
Then, we converted all the characters of str to uppercase using a for loop. The loop runs from i = 0 to i = strlen(str) - 1.
for (int i = 0; i < strlen(str); i++) {
...
}
In other words, the loop iterates through the whole string since strlen() gives the length of str.
In each iteration of the loop, we convert the string element str[i] (a single character of the string) to uppercase and store it in the char variable ch.
ch = toupper(str[i]);
We then print ch inside the loop. By the end of the loop, the entire string has been printed in uppercase.