-1

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?

cadaniluk
  • 15,027
  • 2
  • 39
  • 67
Amai
  • 51
  • 2
  • 11

2 Answers2

0

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 .

tmlen
  • 8,533
  • 5
  • 31
  • 84
0

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";
David Schwartz
  • 179,497
  • 17
  • 214
  • 278