[英]for loop c++ 'toupper' implementation
有人可以解释为什么 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编程。
toupper
返回int
。 您需要将返回值char
为char
,以便输出流运算符<<
打印出字符,而不是其数字值。
您还应该将输入转换为unsigned char
,以覆盖char
被签名且字符集包含负数的情况(这将在toupper
调用未定义的行为 )。 例如,
cout << static_cast<char>(toupper(static_cast<unsigned char>(c)));
请注意,您需要包括相关的标头(如果要std::toupper
cctype
如果要C的toupper
ctype.h
。)
它正在打印ASCII值(整数)。 我同意@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() 返回整数值
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.