I want an 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 the debugging to a file like this: ./myprog 2>out.txt
.
If I don't ask too much I would like to receive explanations too.
Thanks!
The "c" in cerr refers to "character" and "err" means "error". Hence cerr means "character error". The cerr object is used along with the insertion operator << in order to display error messages.
The main difference is that printf() is used to send formated string to the standard output, while cout doesn't let you do the same, if you are doing some program serious, you should be using printf(). As pointed out above, printf is a function, cout an object.
Answer: Yes. Printf can be used in C++. To use this function in a C++ program, we need to include the header <cstdio> in the program.
Use fprintf(stderr, ...)
, e.g.:
fprintf(stderr, "%2.2x", var[i]);
You can do this with the 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 have a play around, and some more are listed here: http://www.cplusplus.com/reference/iomanip/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With