有人可以解释为什么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
以便输出流运算符<<
打印出字符而不是其数值。
您还应该将输入转换为 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() 返回整数值