如何在c++中显示字符值为字符串

how to display char value as string in c++?

本文关键字:字符 字符串 显示 c++      更新时间:2023-10-16

我有一个简单的字符变量,如下所示:

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";