【问题标题】:How to clear width when outputting from a stream, after using std::setw?使用std :: setw后如何在从流输出时清除宽度?
【发布时间】:2012-11-21 15:22:18
【问题描述】:

我正在使用 std::stringstream 将固定格式的字符串解析为值。但是最后要解析的值不是固定长度的。

要解析这样的字符串,我可能会这样做:

std::stringstream ss("123ABCDEF1And then the rest of the string");
ss >> std::setw(3) >> nId
   >> std::setw(6) >> sLabel
   >> std::setw(1) >> bFlag
   >> sLeftovers;

但是如何设置宽度以便输出字符串的其余部分?

通过反复试验,我发现这样做很有效:

   >> std::setw(-1) >> sLeftovers;

但是正确的方法是什么?

【问题讨论】:

  • "通过这样做:std::setw(-1)" 你的意思是sLeftovers 包含值'And'还是'And then the rest of the string'?我发现 'std::setw(-1)` 只检索单词“And”,即与 '>> sLeftovers' 相同的结果 - 它没有影响,这与 std::setw 的文档一致,该文档指出 @ 987654327@ 设置用作下一次插入操作的字段的字符数。
  • 你说得对,马克,在我的实际代码中,数据中没有空格。

标签: c++ stringstream iomanip setw


【解决方案1】:

请记住,输入运算符 >> 在空白处停止读取。

使用例如std::getline 获取字符串的剩余部分:

std::stringstream ss("123ABCDEF1And then the rest of the string");
ss >> std::setw(3) >> nId
   >> std::setw(6) >> sLabel
   >> std::setw(1) >> bFlag;
std::getline(ss, sLeftovers);

【讨论】:

    【解决方案2】:

    std::setw 只影响一个操作,即>> bFlag 会将其重置为默认值,因此您无需执行任何操作来重置它。

    即您的代码应该可以正常工作

    std::stringstream ss("123ABCDEF1And then the rest of the string");
    ss >> std::setw(3) >> nId
       >> std::setw(6) >> sLabel
       >> std::setw(1) >> bFlag
       >> sLeftovers;
    

    【讨论】:

    • 它没有,我的代码中的 sLeftovers 是 1 个字符“A”(属于“And...”)。你确定 std::setw “只影响一个操作”吗?
    【解决方案3】:

    试试这个:

    std::stringstream ss("123ABCDEF1And then the rest of the string");
    std::stringstream::streamsize initial = ss.width(); // backup
    ss >> std::setw(3) >> nId
       >> std::setw(6) >> sLabel
       >> std::setw(1) >> bFlag
       >> sLeftovers;
    
    ss.width(initial); // restore
    

    【讨论】:

      【解决方案4】:

      我很惊讶setw(-1) 实际上对你有用,因为我没有看到这个文档,当我在 VC10 上尝试你的代码时,我只得到了 sLeftovers 的“和”。我可能会使用 std::getline( ss, sLeftovers ) 作为字符串的其余部分,这在 VC10 中对我有用。

      【讨论】:

        猜你喜欢
        • 2017-07-20
        • 2021-12-02
        • 1970-01-01
        • 1970-01-01
        • 2021-11-16
        • 2013-10-21
        • 1970-01-01
        • 2020-06-14
        • 1970-01-01
        相关资源
        最近更新 更多