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

时间:2012-11-21 15:22:19

标签: c++ stringstream iomanip setw

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

但是什么是正确的方法?

4 个答案:

答案 0 :(得分: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);

答案 1 :(得分: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;

答案 2 :(得分: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

答案 3 :(得分:0)

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

相关问题