简体   繁体   中英

C++ “toupper” not converting character to uppercase

I'm trying to convert every letter in a string to uppercase. I'm looping through each character and using toupper on it. However, when I print the new string out, it's not working. Sorry if this is a newbie question. Any help would be greatly appreciated:)

#include <iostream>
#include <algorithm>

using namespace std;

int main()
{
    string str1, str2;
    cin >> str1 >> str2;
    int len = str1.size();

    for (int i = 0; i < len; i++) {
        toupper(str1[i]);
        toupper(str2[i]);
        cout << str1[i] << " " << str2[i] << endl;
    }
}

std::toupper returns a value rather than modifying its argument. So you need to do:

str1[i] = std::toupper(str1[i]);
str2[i] = std::toupper(str2[i]);

in order to actually modify the strings.

If you turn on warnings, eg with -Wall the compiler will tell you that your version of the code has no effect.

You need to save the modified strings back into the str arrays. Something like this:

str[i] = toupper(str[i]);

This may be better, depending on your coding standards:

std::transform(str1.begin(), str1.end(), str1.begin(), std::toupper);
std::transform(str2.begin(), str2.end(), str2.begin(), std::toupper);

The above uses the STL function transform to convert the string to all uppercase.

In your loop, you don't change the elements of the strings because toupper() returns a new character, it doesn't change the passed character. You need to make your elements be the same as the returned characters, as follows:

for (int i = 0; i < len; i++) {
    str1[i] = toupper(str1[i]);
    str2[i] = toupper(str2[i]);
    cout << str1[i] << " " << str2[i] << endl;
}

For starters this loop

for (int i = 0; i < len; i++) {
    toupper(str1[i]);
    toupper(str2[i]);
    cout << str1[i] << " " << str2[i] << endl;
}

can invoke undefined behavior because the strings str1 and str2 in general can have different lengths.

These calls

    toupper(str1[i]);
    toupper(str2[i]);

has no effect because they change neither str1[i] no str2[i] .

Also you need to convert the argument of a call of toupper to the type unsigned char .

You could separately output each string the following way

for ( unsigned char c : str1 )
{
    std::cout << ::toupper( c );
}
std::cout << ' ';

for ( unsigned char c : str2 )
{
    std::cout << ::toupper( c );
}
std::cout << '\n';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM