相关疑难解决方法(0)

哪个iomanip操纵器"粘"?

我最近遇到了一个问题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()
  • 最后有一个在线参考,清楚地记录了这种行为?我的供应商文档(MS Visual Studio 2005)似乎没有清楚地显示这一点.

c++ c++-faq

134
推荐指数
3
解决办法
3万
查看次数

"永久"std :: setw

有没有办法永久设置std::setw操纵器(或其功能width)?看这个:

#include <iostream>
#include <iomanip>
#include <algorithm>
#include <iterator>

int main( void )
{
  int array[] = { 1, 2, 4, 8, 16, 32, 64, 128, 256 };
  std::cout.fill( '0' );
  std::cout.flags( std::ios::hex );
  std::cout.width( 3 );

  std::copy( &array[0], &array[9], std::ostream_iterator<int>( std::cout, " " ) );

  std::cout << std::endl;

  for( int i = 0; i < 9; i++ )
  {
    std::cout.width( 3 );
    std::cout << array[i] << " ";
  }
  std::cout << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

跑完后,我看到:

001 …
Run Code Online (Sandbox Code Playgroud)

c++ templates setw

30
推荐指数
2
解决办法
1万
查看次数

标签 统计

c++ ×2

c++-faq ×1

setw ×1

templates ×1