2015-10-19 85 views
-1

所以我有一个简单的字符变量,如下所示:如何在C++中显示char值为字符串?

char testChar = 00000; 

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

+1

'00000'是一样的'0'这是一样的' \ 0'。所以不行。 – juanchopanza

+1

无论你如何拼写,值都是0。如果你想保留你想要的拼写'string test =“00000”; '。 –

+3

'std :: string testString =“00000”;' –

回答

0

要打印char的整数值:

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

不投,它会调用operator<<char的说法,它打印的字符。

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”,“00”或“1-1”,但它是相同的值并且是相同的字符。

如果要输出字符串“0000”,如果一个角色的值为零,你可以做这样的:

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