所以我有一個簡單的字符變量,如下所示:如何在C++中顯示char值爲字符串?
char testChar = 00000;
現在,我的目標是不顯示的Unicode字符,但本身的價值(這是"00000"
)在控制檯中。我怎樣才能做到這一點?是否有可能以某種方式將其轉換爲字符串?
所以我有一個簡單的字符變量,如下所示:如何在C++中顯示char值爲字符串?
char testChar = 00000;
現在,我的目標是不顯示的Unicode字符,但本身的價值(這是"00000"
)在控制檯中。我怎樣才能做到這一點?是否有可能以某種方式將其轉換爲字符串?
要打印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"
你是令人困惑的值與表示。該字符的值是數字零。如果需要,可以將其表示爲「零」,「0」,「00」或「1-1」,但它是相同的值並且是相同的字符。
如果要輸出字符串「0000」,如果一個角色的值爲零,你可以做這樣的:
char a;
if (a==0)
std::cout << "0000";
'00000'是一樣的'0'這是一樣的' \ 0'。所以不行。 – juanchopanza
無論你如何拼寫,值都是0。如果你想保留你想要的拼寫'string test =「00000」; '。 –
'std :: string testString =「00000」;' –