简体   繁体   English

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

[英]How to clear width when outputting from a stream, after using std::setw?

I'm using a std::stringstream to parse a fixed format string into values. 我正在使用std :: stringstream将固定格式的字符串解析为值。 However the last value to be parsed is not fixed length. 但是,最后要解析的值不是固定长度。

To parse such a string I might do: 要解析这样的字符串,我可以这样做:

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

But how do I set the width such that the remainder of the string is output? 但是,如何设置宽度以输出字符串的其余部分呢?

Through trial and error I found that doing this works: 通过反复试验,我发现这样做是可行的:

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

But what's the correct approach? 但是正确的方法是什么?

Remember that the input operator >> stops reading at whitespace. 请记住,输入运算符>>停止在空白处读取。

Use eg std::getline to get the remainder of the string: 使用例如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);

std::setw only affects exactly one operation, ie >> bFlag will reset it to default, so you don't need to do anything to reset it. std::setw仅影响一个操作,即>> bFlag会将其重置为默认值,因此您无需执行任何操作即可将其重置。

ie your code should just work 即您的代码应该可以正常工作

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

Try this: 尝试这个:

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

I'm surprised that setw(-1) actually works for you because I haven't seen this documented, and when I tried your code on VC10, I only got "And" for sLeftovers . 令我惊讶的是setw(-1)实际上对您sLeftovers ,因为我没有看到此文档,并且当我在VC10上尝试您的代码时,我只为sLeftovers获得了“ And”。 I'd probably use std::getline( ss, sLeftovers ) for the remainder of the string, which worked for me in VC10. 我可能会在字符串的其余部分使用std::getline( ss, sLeftovers ) ,这在VC10中对我有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM