简体   繁体   中英

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

So I have a simple char variable which is as follows:

char testChar = 00000;

Now, my goal is to display not the unicode character, but the value itself (which is "00000" ) in the console. How can I do that? Is it possible to convert it to a string somehow?

To print the char 's integer value:

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

Without the cast, it calls the operator<< with char argument, which prints the character.

char is an integer type, and only stores the number, not the format (" 00000 ") used in the definition. To print a number with padding:

#include <iomanip>
std::cout << std::setw(5) << std::setfill(' ') << static_cast<int>(testChar) << std::endl;
// prints "00000"

See http://en.cppreference.com/w/cpp/io/manip/setfill .

To convert it to a std::string containing the formatted character number, you can use 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"

See http://en.cppreference.com/w/cpp/io/basic_stringstream .

You are confusing values with representations. The character's value is the number zero. You can express this as "zero", "0", "00", or "1-1" if you want, but it's the same value and it's the same character.

If you want to output the string "0000" if a character's value is zero, you can do it like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM