用C++; 在C++代码中,我有一个双变量矩阵,我打印出来。但是,由于它们的位数不同,因此输出格式会被破坏。一个解决办法是 cout.precision(5)但我希望不同的列具有不同的精度。此外,由于在某些情况下存在负值,-符号的存在也会导致问题。如何绕过此问题并生成正确格式的输出?

用C++; 在C++代码中,我有一个双变量矩阵,我打印出来。但是,由于它们的位数不同,因此输出格式会被破坏。一个解决办法是 cout.precision(5)但我希望不同的列具有不同的精度。此外,由于在某些情况下存在负值,-符号的存在也会导致问题。如何绕过此问题并生成正确格式的输出?,c++,output-formatting,C++,Output Formatting,使用 从样本: 看看流,尤其是std::setw和std::setfill float f = 3.1415926535; std::cout << std::setprecision(5) // precision of floating point output << std::setfill(' ') // character used to fill the column << std::setw(

使用

从样本:

看看流,尤其是
std::setw
std::setfill

float f = 3.1415926535;
std::cout << std::setprecision(5)   // precision of floating point output
          << std::setfill(' ')      // character used to fill the column
          << std::setw(20)          // width of column
          << f << '\n';             // your number
float f=3.1415926535;

std::cout尝试使用setw操纵器。有关更多信息,请参阅

有一种使用i/o操纵器的方法,但我发现它很难使用。我只想写一个这样的函数:

template<typename T>
std::string RightAligned(int size, const T & val)
{
    std::string x = boost::lexical_cast<std::string>(val);
    if (x.size() < size)
        x = std::string(size - x.size(), ' ') + x;
    return x;
}
std::cout << std::setw(5) << 0.2 << std::setw(10) << 123456 << std::endl;
std::cout << std::setw(5) << 0.12 << std::setw(10) << 123456789 << std::endl;
模板
标准::字符串右对齐(整数大小、常量T和val)
{
std::string x=boost::词法转换(val);
如果(x.size()
在我的头顶上,可以使用setw(int)指定输出的宽度

像这样:

template<typename T>
std::string RightAligned(int size, const T & val)
{
    std::string x = boost::lexical_cast<std::string>(val);
    if (x.size() < size)
        x = std::string(size - x.size(), ' ') + x;
    return x;
}
std::cout << std::setw(5) << 0.2 << std::setw(10) << 123456 << std::endl;
std::cout << std::setw(5) << 0.12 << std::setw(10) << 123456789 << std::endl;

正如其他人所说,关键是使用操纵器。他们 忽略的是,你通常使用你写的操纵器 你自己
FFmt
操纵器(与中的
F
格式相对应 Fortran相当简单:

class FFmt
{
    int myWidth;
    int myPrecision;
public:
    FFmt( int width, int precision )
        : myWidth( width )
        , myPrecision( precision )
    {
    }

    friend std::ostream& 
    operator<<( std::ostream& dest, FFmt const& fmt )
    {
        dest.setf( std::ios_base::fixed, std::ios_base::formatfield );
        dest.precision( myPrecision );
        dest.width( myWidth );
        return dest;
    }
};
并写下:

std::cout  << col1 << value1
    << ' ' << col2 << value2...

std::不记得您需要包含才能找到setw()@user1603472是的,但我的代码没有使用
std::setw
。对不起,我的错,我点击了错误的位置,是一个快速的注释,仅供参考:在执行std::setw(x)时确保x大于十进制精度。这是正确的答案,但如果没有额外的库,它在Ubuntu(gcc)上无法工作:
#include
。请在此处检查:
FFmt col1( 8, 2 );
FFmt col2( 6, 3 );
//  ...
std::cout  << col1 << value1
    << ' ' << col2 << value2...