1

有人可以解释为什么这个 C++ 中的短代码不会产生预期的输出。该代码应该以大写字母打印字符串。

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

int main(){
    string sample("hi, i like cats and dogs.");
    cout << "small: " << sample << endl << "BIG  : ";

    for(char c: sample)
        cout << toupper(c);
    cout<<endl;

return 0;
}

上述程序的输出是:

small: hi, i like cats and dogs.
BIG  : 72734432733276737569326765848332657868326879718346

但我期望:

small: hi, i like cats and dogs.
BIG  : HI, I LIKE CATS AND DOGS.

我只用python编程过。

4

3 回答 3

8

toupper返回int。您需要将返回值转换为char,以便输出流运算符<<打印出字符而不是其数值。

您还应该将输入转换为unsigned char, 以涵盖char已签名且您的字符集包含负数的情况(这将在 中调用未定义的行为toupper)。例如,

cout << static_cast<char>(toupper(static_cast<unsigned char>(c)));

请注意,您需要包含相关的标题(cctype如果您想要std::toupperctype.h如果您想要 C 的toupper。)

于 2015-06-14T22:39:26.360 回答
0

它正在打印整数的 ASCII 值。我同意@Captain Obvlious。

于 2015-06-14T22:41:37.157 回答
0
#include <iostream>
#include <string>
using namespace std;

int main(){
    string sample("hi, i like cats and dogs.");
    cout << "small: " << sample << endl << "BIG  : ";

    for(char c: sample)
        cout << (char)toupper(c);
    cout<<endl;

return 0;
}

// toupper() 返回整数值

于 2021-07-04T05:18:06.630 回答