相关疑难解决方法(0)

"永久"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++输出流中设置宽度

我试图通过设置不同字段的宽度在C++上创建一个整齐格式的表.我可以使用setw(n),做类似的事情

cout << setw(10) << x << setw(10) << y << endl;
Run Code Online (Sandbox Code Playgroud)

或更改ios_base :: width

cout.width (10);
cout << x;
cout.width (10);
cout << y << endl;
Run Code Online (Sandbox Code Playgroud)

问题是,这两种选择都不允许我设置默认的最小宽度,每次我都要向流写入内容时我必须更改它.

有没有人知道我可以做到这一点而无需无数次重复同一次呼叫?提前致谢.

c++ width

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

format,iomanip,c ++

我正在努力学习使用名称空间声明比使用"使用命名空间标准"更明确.我正在尝试将我的数据格式化为2位小数,并将格式设置为固定而非科学.这是我的主要文件:

#include <iostream>
#include <iomanip>

#include "SavingsAccount.h"
using std::cout;
using std::setprecision;
using std::ios_base;

int main()
{
    SavingsAccount *saver1 = new SavingsAccount(2000.00);
    SavingsAccount *saver2 = new SavingsAccount(3000.00);

    SavingsAccount::modifyInterestRate(.03);

    saver1->calculateMonthlyInterest();
    saver2->calculateMonthlyInterest();

    cout << ios_base::fixed << "saver1\n" << "monthlyInterestRate: " << saver1->getMonthlyInterest()
        << '\n' << "savingsBalance: " << saver1->getSavingsBalance() << '\n';
    cout << "saver2\n" << "monthlyInterestRate: " << saver2->getMonthlyInterest()
        << '\n' << "savingsBalance: " << saver2->getSavingsBalance() << '\n';
}
Run Code Online (Sandbox Code Playgroud)

在Visual Studio 2008上,当我运行程序时,在我想要的数据之前得到输出"8192".这有什么理由吗?

另外,我认为我没有正确设置固定部分或2位小数,因为一旦我添加了setprecision(2),我似乎得到了科学记数法.谢谢.

c++ iomanip

7
推荐指数
1
解决办法
6380
查看次数

标签 统计

c++ ×3

iomanip ×1

setw ×1

templates ×1

width ×1