【问题标题】:C++ - cout flags work only for first outputC++ - cout 标志仅适用于第一个输出
【发布时间】:2014-03-09 17:04:36
【问题描述】:

当我传递一些数据时,输出类似于xxxxxxxx0x97 0x104 0x111 0x106 0x0 为什么 cout 格式只影响第一个输出?

void Dumper::hex(const unsigned char * data, size_t len) {

        cout << endl;

        ios::fmtflags f(cout.flags());

        /*
        cout.fill('0');
        cout.width(2);
        */

        cout.fill('x');
        cout.width(10);

        for (int i = 0; i < len; i++) {
            cout << "0x" << ((long)(data[i]) & 255) << " ";
        }

        cout.flags(f);
        cout << endl;

    }

【问题讨论】:

  • width() 在插入后被重置。在循环中使用std::setw
  • 顺便说一句,您输出“0x”后跟十进制值,如果您想以十六进制输出,请执行cout &lt;&lt; std::hex

标签: c++ formatting iostream


【解决方案1】:

width() 被任何使用它的操作重置为 0。基本思想是它不太可能适用于多个领域。特别是,它不太可能适用于值和分隔符。因此,应在每个值之前设置宽度。

对于您的特定用途,我会使用 std::internalstd::showbase。还要确保将unsigned 值用于您的两位十六进制值:否则您将得到扩展符号。

【讨论】:

    猜你喜欢
    • 2021-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-07
    • 1970-01-01
    • 2023-03-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多