我想让cout输出一个前导为零的int,因此1将被打印为001,25将被打印为025。我该怎么做呢?


当前回答

在c++ 20中,你可以做到:

std::cout << std::format("{:03}", 25); // prints 025

在此期间,您可以使用{fmt}库,std::format是基于。

免责声明:我是{fmt}和c++ 20 std::format的作者。

其他回答

在c++ 20中,你可以做到:

std::cout << std::format("{:03}", 25); // prints 025

在此期间,您可以使用{fmt}库,std::format是基于。

免责声明:我是{fmt}和c++ 20 std::format的作者。

在单个数字值的实例上使用零作为填充字符输出日期和时间的另一个示例:2017-06-04 18:13:02

#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <ctime>
using namespace std;

int main()
{
    time_t t = time(0);   // Get time now
    struct tm * now = localtime(&t);
    cout.fill('0');
    cout << (now->tm_year + 1900) << '-'
        << setw(2) << (now->tm_mon + 1) << '-'
        << setw(2) << now->tm_mday << ' '
        << setw(2) << now->tm_hour << ':'
        << setw(2) << now->tm_min << ':'
        << setw(2) << now->tm_sec
        << endl;
    return 0;
}
cout.fill( '0' );    
cout.width( 3 );
cout << value;

另一种实现方法是使用C语言的旧printf()函数

你可以用这个

int dd = 1, mm = 9, yy = 1;
printf("%02d - %02d - %04d", mm, dd, yy);

这将在控制台上打印09 - 01 - 0001。

你也可以使用另一个函数sprintf()将格式化的输出写入如下所示的字符串:

int dd = 1, mm = 9, yy = 1;
char s[25];
sprintf(s, "%02d - %02d - %04d", mm, dd, yy);
cout << s;

不要忘记在这两个函数的程序中包含stdio.h头文件

注意事项:

可以用0或另一个字符(不是数字)填充空格。 如果你确实写了%24d这样的格式说明符,那么这将不会在空格中填充2。这将设置pad为24,并填充空白区域。

cout.fill('*');
cout << -12345 << endl; // print default value with no field width
cout << setw(10) << -12345 << endl; // print default with field width
cout << setw(10) << left << -12345 << endl; // print left justified
cout << setw(10) << right << -12345 << endl; // print right justified
cout << setw(10) << internal << -12345 << endl; // print internally justified

这将产生输出:

-12345
****-12345
-12345****
****-12345
-****12345