简体   繁体   English

将格式化的printf(c)等效于C ++中的格式化cerr

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

I want an equivalent for printf("%2.2x", var); 我想要一个等效的printf("%2.2x", var); to cerr<< in C++. 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 . 我的想法是将调试重定向到这样的文件: ./myprog 2>out.txt
If I don't ask too much I would like to receive explanations too. 如果我不要求太多,我也想收到解释。
Thanks! 谢谢!

使用fprintf(stderr, ...) ,例如:

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

You can do this with the stream manipulators in C++, for example: 您可以使用C ++中的流操纵器执行此操作,例如:

#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/ 认为 setw在这里是正确的,但是有一个游戏,还有一些在这里列出: http//www.cplusplus.com/reference/iomanip/

另一种方法是使用boost::format

std::cerr << boost::format("%2.2x") % static_cast<int>(var[i]);
#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 a temporary ostream sharing cerr 's buffer to make sure none of the manipulators leave undesired side effects on cerr . 我使用临时的ostream共享cerr的缓冲区,以确保没有任何操纵器对cerr留下不希望的副作用。 The static_cast is needed because when ostream gets a ( signed or unsigned or plain) char , it thinks it can just copy it as a raw byte. static_cast是必需的,因为当ostream获得( signedunsigned或plain) char ,它认为它只能将其复制为原始字节。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM