如何在c++中显示字符值为字符串
how to display char value as string in c++?
我有一个简单的字符变量,如下所示:
char testChar = 00000;
现在,我的目标不是在控制台上显示unicode字符,而是显示值本身(即"00000"
)。我该怎么做呢?有可能把它转换成字符串吗?
打印char
的整数值:
std::cout << static_cast<int>(testChar) << std::endl;
// prints "0"
如果没有强制转换,则使用char
参数调用operator<<
,并打印字符。
char
是一个整数类型,只存储数字,而不存储定义中使用的格式(" 00000
")。打印带有填充的数字:
#include <iomanip>
std::cout << std::setw(5) << std::setfill(' ') << static_cast<int>(testChar) << std::endl;
// prints "00000"
参见http://en.cppreference.com/w/cpp/io/manip/setfill。
要将其转换为包含格式化字符号的std::string
,可以使用stringstream
:
#include <iomanip>
#include <sstream>
std::ostringstream stream;
stream << std::setw(5) << std::setfill(' ') << static_cast<int>(testChar);
std::string str = stream.str();
// str contains "00000"
参见http://en.cppreference.com/w/cpp/io/basic_stringstream
您混淆了值和表示。字符的值是数字0。您可以将其表示为"0","0","00"或"1-1",但它是相同的值,并且是相同的字符。
如果你想在一个字符的值为0时输出字符串"0000",你可以这样做:
char a;
if (a==0)
std::cout << "0000";
相关文章:
- 从 argv[1] 转换为字符 * 字符串后有什么问题?
- 将 NULL 与 C 的字符* 字符串一起使用
- 无法在声明时使用初始值设定项列表初始化常量字符*/字符串数组的向量
- 无法将常量字符字符串传递给模板类
- 如何组合一个宽字符字符串,中间插入一些空字符
- 如何将二维数组类型字符(字符串)作为函数参数传递?
- 从给定索引返回子字符字符串的函数
- 字符 [](c 字符串)的初始化标准
- 如何将字符字符串用作数学运算符
- 将 Unicode 字符/字符串写入文件
- C++,字符* 字符串修改
- 如何有效地用不同的整数元素替换字符字符串的元素
- C++:如果我们在字符串中添加一些整数,为什么它会从开头删除该数量的字符?(字符串 + 整数)
- strcpy正在复制sth字符i字符串.如何解决此错误
- 在C++中将双精度转换为字符*/字符串
- C 中的宽字符字符串
- 如何提取C 中的字符/字符串之间的字符串
- 无法将字符/字符串转换为int
- 带有指针的反转字符字符串
- 反转字符串中的 n 个字符(字符串中没有空格),而不使用 c++ 中的内置函数