什么是C ++相当于C格式“%3d”?

时间:2014-05-22 17:18:09

标签: c++

我的代码是:

#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++;
    }
}

4 个答案:

答案 0 :(得分:3)

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=%3d\n", count, total); 
    count++;
  }
}

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

请注意,stdio.hiostream 输入接口都不适合用途,因为定义数字输入溢出等恶劣的标准编码错误会触发未定义的行为(我不是这样做的!)

答案 1 :(得分:3)

使用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++;
    }
}

答案 2 :(得分:1)

您可以使用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 impression”(在这种情况下为15)和left的设置,只需将对齐设置在左侧。

注意:根据@Zack的建议,您最后可以在<< '\n'写下<< endl。由于<< endl与编写<< '\n' << flush完全相同,因此在这种情况下不需要刷新。

答案 3 :(得分:0)

在C ++中,IO格式化的方式与C中的格式相同(因为C ++中的所有C功能都已到位)或者std::setw std::setprecission和其他C ++ manipulators在标题中。

所以其中任何一个都没关系:

#include <cstdio>

int main()
{
    int count=0;
    int total=0;

    while( count <= 10)
    {
        total += count;
        printf( "count = %3d, total = %3d\n", 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进行自定义格式设置,以将自定义构面应用于locale(即扩展std :: numpunct)。

http://ideone.com/nHfTL6