用于循环 C++ 'toupper'实现
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
以便输出流运算符<<
打印出字符而不是其数值。
您还应该将输入转换为 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() 返回整数值
相关文章:
- 如果没有malloc,链表实现将失败
- 如何在c++中实现处理器调度模拟器
- 如何在c++中使用引用实现类似python的行为
- 实现无开销push_back的最佳方法是什么
- 使用简单类型列表实现的指数编译时间.为什么
- 如何在BST的这个简单递归实现中消除警告
- 实现一个在集合上迭代的模板函数
- 我应该实现右值推送功能吗?我应该使用std::move吗
- 如何正确实现和访问运算符的各种自定义枚举器
- C++Union/Struct位域的实现和可移植性
- 这个极客对极客的trie实现是否存在内存泄漏问题
- 在c++中实现LinkedList时,应出现未处理的错误
- 为左值和右值的包装器实现C++范围
- 使用模板进行堆栈实现; "name followed by :: must be a class or namespace"
- 使用GSoap实现ONVIF
- 在用于格式4的arm模拟器中实现功能时的一个问题
- 用于AVX的ln(x)的实现,m256
- 用常见虚拟函数实现的任意组合来实现派生类的正确方法是什么
- 在C++中,如何在类和函数(可能是模板化的)的头中编写完整的实现
- 用于循环 C++ 'toupper'实现