Introduction

Converting a string to upper case is a common requirement in C++ programming. Whether you need to compare strings without considering the case or simply want to display text in uppercase, there are a few methods you can use to achieve this. In this tutorial, we will explore a simple and efficient method to convert a string to uppercase in C++.

First, let’s start with a basic example:

#include <iostream>
#include <string>
#include <cctype>

int main() {
    std::string str = ""hello world"";

    // Convert the string to uppercase
    for (char& c : str) {
        c = std::toupper(c);
    }

    // Print the converted string
    std::cout << str << std::endl;

    return 0;
}

In the above code, we include the necessary headers <iostream>, <string>, and <cctype> for string manipulation and character conversion. We then declare a std::string variable str and initialize it with the string ““hello world””.

To convert the string to uppercase, we use a for loop to iterate through each character of the string. The std::toupper() function from the <cctype> header is then called for each character, which converts it to its uppercase equivalent. Note that we modify the string in-place by using a reference to each character char& c in the loop.

Finally, we print the converted string using std::cout.

When you run the above code, it will output:

HELLO WORLD

As you can see, the string ““hello world”” has been successfully converted to uppercase.

It’s important to note that the std::toupper() function works correctly with ASCII characters. However, for characters outside the ASCII range, the behavior may be implementation-defined. If you’re working with non-ASCII characters, you may need to use specific functions or libraries that support Unicode conversions.

In conclusion, converting a string to uppercase in C++ is relatively straightforward. By using the std::toupper() function and iterating through each character of the string, you can easily achieve the desired uppercase representation. Remember to handle non-ASCII characters appropriately based on your specific requirements.

I hope you found this tutorial helpful!