使用std::setw后,如何在输出流中清除宽度?

7

我正在使用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;

但是正确的方法是什么?

可能是重复的问题:如何在不知道应用了哪些操作器的情况下“回滚”或撤消对流的任何操作。原问题链接:https://dev59.com/-W855IYBdhLWcg3wp2J0 - Martin York
通过执行这个命令:std::setw(-1),您是指sLeftovers包含值“And”还是“然后是字符串的其余部分”?我发现std::setw(-1)只检索单词“And”,即与“>> sLeftovers”相同的结果 - 它没有影响,这与std::setw的文档一致,该文档说明std :: setw设置要用作下一个插入操作字段的字符数。 - mark
你说得很对,马克,在我的实际代码中,数据中没有空格。 - DaBozUK
4个回答

3

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

使用例如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);

3

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只有一个字符"A"(来自"And...")。你确定std::setw "只影响一个操作"吗? - DaBozUK

1

试试这个:

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

0
我很惊讶 setw(-1) 对你起作用,因为我还没有看到这被记录下来。当我在 VC10 上尝试你的代码时,sLeftovers 只得到了 "And"。对于字符串的剩余部分,我可能会使用 std::getline(ss, sLeftovers),这在 VC10 中对我有效。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接