Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c

printf

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!

like image 405
George B Avatar asked May 29 '13 16:05

George B


People also ask

What is CERR in c?

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.

Is cout the same as printf?

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.

Can I use printf in C++?

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.


Video Answer


2 Answers

Use fprintf(stderr, ...), e.g.:

fprintf(stderr, "%2.2x", var[i]);
like image 150
nullptr Avatar answered Oct 20 '22 20:10

nullptr


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/

like image 4
slugonamission Avatar answered Oct 20 '22 20:10

slugonamission