gpt4 book ai didi

c++ - 用 setw 对齐文本

转载 作者:行者123 更新时间:2023-11-30 00:37:31 27 4
gpt4 key购买 nike

我想像这样证明输出文本

 0x29823d80    0x10019b8         /    0 00000000000000000000000000000001
0x37449e60 0x10dfc / 12 00000000000000000001000000000000

但是有了这个声明

  fout << std::setw(5) << std::hex << "0x" << (*it).addr << " " 
<< std::setw(5) << std::hex << "0x" << (*it).pc << std::setw(10) << "/" << std::setw(5) << std::dec << (*it).off << "\t"
<< std::setw(5) << (*it).layout << "\n";

我明白了:

0x29823d80    0x10019b8         /    0  00000000000000000000000000000001
0x37449e60 0x10dfc / 12 00000000000000000001000000000000

最佳答案

来自 this reference :

This value is not "sticky": the next input or output operation that is affected by the value of the stream's width field, resets it to zero (meaning "unspecified").

这意味着您所做的setw 是针对字符串"0x" 而不是实际的十六进制数。您必须使用 setw就在您想要证明的输出之前。

编辑:您的问题的一种解决方案是使用包含前导“0x” 的临时字符串,并使用这些字符串的格式:

std::ostringstream val1, val2;

val1 << "0x" << std::hex << (*it).addr;
val2 << "0x" << std::hex << (*it).pc;

fout << val1.str() << " " << val2.str()
<< std::setw(10 + 10 - val2.str().length())
<< '/' ...

上面的表达式 10 + 10 - val2.str().length() 我从这里得到:

  • 第一个 10 因为您似乎想要在数字和斜杠之间有 10 个空格
  • 第二个 10 因为它允许 8 个十六进制数字(32 位)加上前导 “0x”
  • 根据数字字符串的实际长度进行调整

您可以看到使用此方法的示例 here .

关于c++ - 用 setw 对齐文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13159545/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com