【问题标题】:how to display char value as string in c++?如何在 C++ 中将 char 值显示为字符串?
【发布时间】:2015-10-19 21:53:03
【问题描述】:

所以我有一个简单的 char 变量,如下所示:

char testChar = 00000;

现在,我的目标不是在控制台中显示 unicode 字符,而是显示值本身("00000")。我怎样才能做到这一点?是否可以以某种方式将其转换为字符串?

【问题讨论】:

标签: c++ string unicode char


【解决方案1】:

打印char的整数值:

std::cout << static_cast<int>(testChar) << std::endl;
// prints "0"

没有演员表,它调用带有char参数的operator&lt;&lt;,打印字符。

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

【讨论】:

    【解决方案2】:

    您将值与表示混淆了。字符的值是数字零。如果需要,您可以将其表示为“零”、“0”、“00”或“1-1”,但它是相同的值和相同的字符。

    如果你想在一个字符的值为零的情况下输出字符串“0000”,你可以这样做:

    char a;
    if (a==0)
       std::cout << "0000";
    

    【讨论】:

      猜你喜欢
      • 2013-05-13
      • 2014-02-16
      • 2012-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-05
      • 2013-04-06
      • 1970-01-01
      相关资源
      最近更新 更多