tolower()和toupper()的疑问解决方案
tolower()和toupper()的疑问
#include <iostream>
#include <cctype>
#include <string>
using std::string;
int main()
{
string a = "abc ";
for(string::size_type i=0; i!=a.size(); ++i)
std::cout < < toupper(a[i]) < <std::endl;
}
小写字母变为大写输出,结果却输出了65 66 67 但是将上述for循环换成
for(string::size_type i=0; i!=a.size(); ++i)
a[i] = toupper(a[i]);
std::cout < < a < <std::endl;
结果正确,为什么?
------解决方案--------------------
std::cout < < toupper(a[i]) < <std::endl;
改成
std::cout < < (char)toupper(a[i]) < <std::endl;
或者
printf( "%c\n ", toupper(a[i]));
------解决方案--------------------
我觉得最好是
static_cast <char> ( toupper(static_cast <unsigned char> (a[i])) )
------解决方案--------------------
(char)toupper(a[i])
这两个函数的返回值是int,
需要转换到 char 后输出即可。
------解决方案--------------------
touper()的返回值是int
所以std::cout < < toupper(a[i]) < <std::endl;输出的是 数字
变量a你定义的是字符串型
所以a[i] = toupper(a[i]);操作后,编辑器会自动将int 转换为char 赋值给a[i].
#include <iostream>
#include <cctype>
#include <string>
using std::string;
int main()
{
string a = "abc ";
for(string::size_type i=0; i!=a.size(); ++i)
std::cout < < toupper(a[i]) < <std::endl;
}
小写字母变为大写输出,结果却输出了65 66 67 但是将上述for循环换成
for(string::size_type i=0; i!=a.size(); ++i)
a[i] = toupper(a[i]);
std::cout < < a < <std::endl;
结果正确,为什么?
------解决方案--------------------
std::cout < < toupper(a[i]) < <std::endl;
改成
std::cout < < (char)toupper(a[i]) < <std::endl;
或者
printf( "%c\n ", toupper(a[i]));
------解决方案--------------------
我觉得最好是
static_cast <char> ( toupper(static_cast <unsigned char> (a[i])) )
------解决方案--------------------
(char)toupper(a[i])
这两个函数的返回值是int,
需要转换到 char 后输出即可。
------解决方案--------------------
touper()的返回值是int
所以std::cout < < toupper(a[i]) < <std::endl;输出的是 数字
变量a你定义的是字符串型
所以a[i] = toupper(a[i]);操作后,编辑器会自动将int 转换为char 赋值给a[i].