C++ 如何使用操纵器将十六进制输出格式化为带填充的左零

C++ 如何使用操纵器将十六进制输出格式化为带填充的左零,c++,manipulators,C++,Manipulators,下面的小测试程序打印出来: SS编号为=3039 我想把数字打印出来,用左零填充,这样总长度是8。因此: SS编号=00003039(注意左填充的额外零) 我想知道如何使用操纵器和stringstream实现这一点,如下所示。谢谢 测试程序: #include <iostream> #include <sstream> #include <string> #include <vector> int main() { int i = 12

下面的小测试程序打印出来:

SS编号为=3039

我想把数字打印出来,用左零填充,这样总长度是8。因此:

SS编号=00003039(注意左填充的额外零)

我想知道如何使用操纵器和stringstream实现这一点,如下所示。谢谢

测试程序:

#include <iostream>
#include <sstream>
#include <string>
#include <vector>

int main()
{

    int i = 12345;
    std::stringstream lTransport;

    lTransport << "And SS Number IS =" << std::hex << i << '\n';

    std::cout << lTransport.str();

}
#包括
#包括
#包括
#包括
int main()
{
int i=12345;
std::stringstream LTTransport;

LTTransport您看过库的setfill和setw操纵器吗

#include <iomanip>
...
lTransport << "And SS Number IS =" << std::hex << std::setw(8) ;
lTransport << std::setfill('0') << i << '\n';
我将使用:

cout << std::hex << std::setw(sizeof(i)*2) << std::setfill('0') << i << std::endl;
cout您可以使用和函数如下:

#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <iomanip>

using namespace std;

int main()
{    
    int i = 12345;
    std::stringstream lTransport;

    lTransport << "And SS Number IS =" << setfill ('0') << setw (8)<< std::hex << i << '\n';    
    std::cout << lTransport.str();  // prints And SS Number IS =00003039    
}
#包括
#包括
#包括
#包括
#包括
使用名称空间std;
int main()
{    
int i=12345;
std::stringstream LTTransport;

LTTransport如果我在格式化十六进制前后添加内容,填充和宽度如何影响内容?有没有办法让它们只应用于格式化十六进制而不是整个字符串流?我编辑了我的答案以添加代码。我希望它对你有用。哦!看起来像“让我来吧”在设置格式化程序并将整数写入stringstream M后,您可以根据需要重新调整setw()和setfill()。或者,您也可以使用sprintf(char_buf,'%08X',i)预格式化c字符串并将其写入stringstream。您不能说
std::setw(8)
?毕竟,OP是这么说的。@Kristo哦,是的,setw(8)就可以了,我忽略了他总是想要8个字符。这将适用于位大小。
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <iomanip>

using namespace std;

int main()
{    
    int i = 12345;
    std::stringstream lTransport;

    lTransport << "And SS Number IS =" << setfill ('0') << setw (8)<< std::hex << i << '\n';    
    std::cout << lTransport.str();  // prints And SS Number IS =00003039    
}