Equivalent to formatted printf (c) formatted cerr in C ++

I want the equivalent for printf("%2.2x", var); to cerr<< in C ++.
code:

 typedef unsigned char byte; static byte var[10]; for(i=1; i<10; i++) printf("%2.2x", var[i]); 

The idea is to redirect debugging to a file as follows: ./myprog 2>out.txt .
If I do not ask too much, I would also like an explanation.
Thank you

+6
source share
4 answers

Use fprintf(stderr, ...) , for example:

 fprintf(stderr, "%2.2x", var[i]); 
+13
source

You can do this using stream manipulators in C ++, for example:

 #include <iostream> #include <iomanip> ... std::cerr << std::hex << std::setw(2) << std::setprecision(2) << (int)var[i]; 

I think setw is correct here, but there is a game, and some of them are listed here: http://www.cplusplus.com/reference/iomanip/

+4
source

Another way: boost::format :

 std::cerr << boost::format("%2.2x") % static_cast<int>(var[i]); 
+3
source
 #include <iostream> #include <iomanip> void show_a_byte(unsigned char val) { std::ostream out(std::cerr.rdbuf()); out << std::hex << std::setw(2) << std::setprecision(2) << static_cast<unsigned int>(val); } 

I used the ostream cerr temporary clipboard to make sure that none of the manipulators left any unwanted side effects on cerr . static_cast necessary because when ostream receives ( signed or unsigned or plain) char , it believes that it can just copy it as the source byte.

+2
source

Source: https://habr.com/ru/post/946103/


All Articles