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 .