我最近遇到了一个问题stringstream,因为我错误地认为std::setw()这会影响每次插入的字符串流,直到我明确地更改它.但是,插入后总是未设置.
// With timestruct with value of 'Oct 7 9:04 AM'
std::stringstream ss;
ss.fill('0'); ss.setf(ios::right, ios::adjustfield);
ss << setw(2) << timestruct.tm_mday;
ss << timestruct.tm_hour;
ss << timestruct.tm_min;
std::string filingTime = ss.str(); // BAD: '0794'
Run Code Online (Sandbox Code Playgroud)
所以,我有很多问题:
setw()这样?std::ios_base::width()和std::setw()?假设我有这样的代码:
void printHex(std::ostream& x){
x<<std::hex<<123;
}
..
int main(){
std::cout<<100; // prints 100 base 10
printHex(std::cout); //prints 123 in hex
std::cout<<73; //problem! prints 73 in hex..
}
Run Code Online (Sandbox Code Playgroud)
我的问题是,在从函数返回后,是否有任何方法可以将cout的状态"恢复"到原来的状态?(有点像std :: boolalpha和std :: noboolalpha ..)?
谢谢.
我正在使用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;
Run Code Online (Sandbox Code Playgroud)
但是如何设置宽度以便输出字符串的其余部分?
通过反复试验,我发现这样做有效:
>> std::setw(-1) >> sLeftovers;
Run Code Online (Sandbox Code Playgroud)
但是正确的方法是什么?