#include <iostream>
#include <fstream>
#include <locale>
#include <iomanip>
#include <cctype>
int main()
{
constchar file_name[] = __FILE__ ;
if( std::ifstream file{ file_name, std::ios::binary } ) // if the file is opened for input (in binary mode)
{
// set the locale of the file stream (and stdout) to one that uses a suitable ANSI character encoding (this example uses UTF8)
file.imbue( std::locale( "en_US.UTF8" ) ) ; // note: the locale name string is implementation dependant
std::cout.imbue( std::locale( "en_US.UTF8" ) ) ; // note: the locale name is string implementation dependant
std::cout << std::showbase ;
char ch ;
while( file.get(ch) ) // for each char (including white space chars) read from the file
{
constunsignedint v = ch ;
if( std::isprint( ch, std::cout.getloc() ) ) std::cout << "'" << ch << "' " ; // print the literal char if it is printable
else std::cout << " " ;
// print its integer value in decimal and hexadecimal
std::cout << std::setw(4) << std::dec << v << std::setw(5) << std::hex << v << '\n' ;
}
}
}
C++20 adds a nice feature with <format>'s formatting library, similar to C's printf(), that can be used to display a number in binary, octal, hex or decimal notation: