简体   繁体   English

for循环C++'toupper'实现

[英]for loop c++ 'toupper' implementation

Can someone explain why this short code in C++ doesn't produce the expected output.有人可以解释为什么 C++ 中的这段短代码不会产生预期的输出。 The code is supposed to print the string in capital letters.该代码应该以大写字母打印字符串。

#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;
}

The output of the above program is:上面程序的输出是:

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

but I expected:但我预计:

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

I've only programmed in python.我只用python编程。

toupper returns int . toupper返回int You need to cast the return value to char such that the output stream operator << prints out the character and not its numeric value. 您需要将返回值charchar ,以便输出流运算符<<打印出字符,而不是其数字值。

You should also cast the input to unsigned char , to cover the case where char is signed and your character set includes negative numbers (this would invoke undefined behaviour in toupper ). 您还应该将输入转换为unsigned char ,以覆盖char被签名且字符集包含负数的情况(这将在toupper调用未定义的行为 )。 For example, 例如,

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

Note that you need to include the relevant header ( cctype if you want std::toupper or ctype.h if you want C's toupper .) 请注意,您需要包括相关的标头(如果要std::toupper cctype如果要C的toupper ctype.h 。)

It's printing the ASCII values which are integers. 它正在打印ASCII值(整数)。 I agree with @Captain Obvlious. 我同意@Captain Obvlious。

#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() return integer value // toupper() 返回整数值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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