C++ toupper() – Convert String to Uppercase

In this C++ Tutorial we will explore the toupper() function, which can be used to convert a single character to it’s uppercase version. We will proceed to show exactly how one can convert an entire C++ String to uppercase, using the toupper() function.


C++ toupper() Syntax

The C++ toupper() function takes a single parameter, which is an integer representing the ascii value of a char. Don’t worry, you can still pass datatypes of type char. They are just integers in the end after all (Remember the ASCII table).

toupper(int ch);

Example# 1 (Converting a Char)

In this example, we will take a look at how to convert some simple characters in C++ to uppercase. This function will work on both uppercase and lowercase, but it just won’t have any effect on uppercase.

int main() {
    char a = 'a';
    char b = 'b';
    char c = 'c';

    cout << toupper(a) << endl;
    cout << toupper(b) << endl;
    cout << toupper(c) << endl;
}

The output:

65
66
67

If you want the output to be in the form of actual characters, you can use typecasting, and convert the int value to its’ character representation.

int main() {
    string var = "Hello World";
    char a = 'a';
    char b = 'b';
    char c = 'c';

    cout << (char) toupper(a) << endl;
    cout << (char) toupper(b) << endl;
    cout << (char) toupper(c) << endl;
}

The output:

A
B
C

Alternatively, you can just store the int value returned into a char variable, which will print out an actual character if you try printing it.


Example# 2 (Converting a String)

In this example we will take a look at how to convert a String to Uppercase. The toupper() function does not work on strings natively, but remember that a String is merely a collection of characters. Hence, with the following approach, where iterate over each individual character in a String, we can convert it to uppercase.

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


int main() {
    string var = "hello world";

    for (int i = 0; i < var.length(); i++) {
        var[i] = toupper(var[i]);
    }

    cout << "New String: " << var << endl;
}

The output:

New String: HELLO WORLD

Alternatives

There are other alternatives for converting a C++ string to Uppercase. You can find a complete C++ String to Uppercase tutorial + examples here.


This marks the end of the C++ toupper(), Converting String to Uppercase Tutorial. Any suggestions or contributions for CodersLegacy are more than welcome. Questions regarding the tutorial content will be asked in the comments section below.

Leave a Comment