C++相当于 C 格式化"%3d"是什么?

What is the C++ equivalent to C formatting "%3d"?

本文关键字:%3d 是什么 格式化 相当于 C++      更新时间:2023-10-16
我的代码是:
#include<iostream>
using namespace std;
int main()
{
    int count=0;
    int total=0;
    while(count<=10)
    {   
        total=total+count;   
        cout<<"count"<<"="<<count/*<<','*/<<'t'<<'t'<<"total"<<"="<<total<<endl;
        count++;
    }
}

使用iostream格式,您需要包括iomanip标头并使用setwsetfill,如下所示:

#include <iostream>
#include <iomanip>
int main() {
    using namespace std;
    int count=0;
    int total=0;
    while(count<=10)
    {   
        total=total+count;   
        cout<<"count"<<"="<<count<<'t'<<'t'<<"total"<<"="<<setfill(' ')<<setw(3)<<total<<endl;
        count++;
    }
}

C标准库的所有功能在c++中仍然可用。你可以这样写你的程序:

#include <cstdio>
using std::printf;
int main()
{
  int count = 0;
  int total = 0;
  while (count<=10)
  {   
    total = total + count;
    printf("count=%3d, total=%3dn", count, total); 
    count++;
  }
}

我个人认为,stdio.h输出接口几乎总是比iostream输出接口更容易使用,并产生更可读的代码,特别是对于格式化的数字输出(如在本例中),所以我会毫不犹豫地这样做。iostream的主要优点是它可以通过operator<<重载扩展为格式化对象,但是像这样的程序不需要这样做。

请注意,stdio.hiostream 输入接口都不适合使用,因为存在令人震惊的标准编码错误,例如定义数字输入溢出以触发未定义行为(我不是在编造这个!)

您可以使用iomanip中的setwleft来实现您想要的效果。

#include <iostream>
#include <iomanip>
int main()
{
    int count=0;
    int total=0;
    while(count<=10)
    {
        total=total+count;
        std::cout << "count = " << std::setw(15) << std::right << count << "total = " << total << std::endl;
        count++;
    }
}

setw设置下一个"cout印象"的宽度(在本例中为15),left仅设置左对齐

注意:根据@Zack的建议,你可以在末尾写<< 'n'而不是<< endl。由于<< endl与写入<< 'n' << flush完全相同,因此在这种情况下不需要刷新

在c++中,IO格式化的方式与C中相同(因为所有C的功能也在c++中存在),或者使用std::setw std::setprecission和header中提供的其他c++操作符。

所以这两个都可以:

#include <cstdio>
int main()
{
    int count=0;
    int total=0;
    while( count <= 10)
    {
        total += count;
        printf( "count = %3d, total = %3dn", count++, total);
    }
}

#include <iostream>
#include <iomanip>
int main()
{
    int count=0;
    int total=0;
    while( count <= 10)
    {
        total += count;
        std::cout << "count = " << std::setw(15) << 
                        count++ << "total = " << total << std::endl;
    }
    return 0;
}

您也可以通过imbue进行自定义格式化,以将自定义facet应用于区域设置(即扩展std::numpunct)。

http://ideone.com/nHfTL6