C ++“ toupper”未将字符转换为大写

问题描述

我正在尝试将字符串中的每个字母都转换为大写。我正在遍历每个字符并在其上使用toupper。但是,当我打印出新字符串时,它不起作用。抱歉,这是一个新手问题。任何帮助将不胜感激:)

#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返回一个值,而不是修改其参数。所以你需要做:

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

以便实际修改字符串。

如果您打开警告,例如使用-Wall,编译器会告诉您您的代码版本无效。

,

您需要将修改后的字符串保存回str数组中。像这样:

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

在循环中,您不会更改字符串的元素,因为toupper()返回一个新字符,它不会更改传递的字符。您需要使元素与返回的字符相同,如下所示:

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

这可能更好,具体取决于您的编码标准:

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

上面使用STL函数transform将字符串转换为全部大写。

,

对于初学者而言,此循环

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

可以调用未定义的行为,因为字符串str1str2通常可以具有不同的长度。

这些电话

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

没有任何效果,因为它们既没有更改str1[i]也没有更改str2[i]

此外,您需要将toupper的调用参数转换为类型unsigned char

您可以按照以下方式分别输出每个字符串

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

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