如何在使用cout<<时使用前导零填充int。运营商?

时间:2009-11-11 11:12:07

标签: c++ formatting cout

我希望cout输出带前导零的int,因此值1将打印为001,值25打印为025 。我怎么能这样做?

7 个答案:

答案 0 :(得分:329)

首先包括<iomanip>,然后是:

cout << setfill('0') << setw(5) << 25;

output:
00025
默认情况下,

setfill设置为space ' 'setw设置要打印的字段的宽度,就是这样。


如果您有兴趣知道如何格式化输出流一般,我写了另一个问题的答案,希望它是有用的: Formatting C++ Console Output.

答案 1 :(得分:39)

实现此目的的另一种方法是使用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并填充空格。

答案 2 :(得分:30)

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

答案 3 :(得分:17)

cout.fill( '0' );    
cout.width( 3 );
cout << value;

答案 4 :(得分:6)

在C ++ 20中,您可以执行以下操作:

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

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

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

答案 5 :(得分:3)

我会使用以下功能。我不喜欢sprintf;它没有做我想要的!!

#define hexchar(x)    ((((x)&0x0F)>9)?((x)+'A'-10):((x)+'0'))
typedef signed long long   Int64;

// Special printf for numbers only
// See formatting information below.
//
//    Print the number "n" in the given "base"
//    using exactly "numDigits".
//    Print +/- if signed flag "isSigned" is TRUE.
//    Use the character specified in "padchar" to pad extra characters.
//
//    Examples:
//    sprintfNum(pszBuffer, 6, 10, 6,  TRUE, ' ',   1234);  -->  " +1234"
//    sprintfNum(pszBuffer, 6, 10, 6, FALSE, '0',   1234);  -->  "001234"
//    sprintfNum(pszBuffer, 6, 16, 6, FALSE, '.', 0x5AA5);  -->  "..5AA5"
void sprintfNum(char *pszBuffer, int size, char base, char numDigits, char isSigned, char padchar, Int64 n)
{
    char *ptr = pszBuffer;

    if (!pszBuffer)
    {
        return;
    }

    char *p, buf[32];
    unsigned long long x;
    unsigned char count;

    // Prepare negative number
    if (isSigned && (n < 0))
    {
        x = -n;
    }
    else
    {
        x = n;
    }

    // Set up small string buffer
    count = (numDigits-1) - (isSigned?1:0);
    p = buf + sizeof (buf);
    *--p = '\0';

    // Force calculation of first digit
    // (to prevent zero from not printing at all!!!)
    *--p = (char)hexchar(x%base);
    x = x / base;

    // Calculate remaining digits
    while(count--)
    {
        if(x != 0)
        {
            // Calculate next digit
            *--p = (char)hexchar(x%base);
            x /= base;
        }
        else
        {
            // No more digits left, pad out to desired length
            *--p = padchar;
        }
    }

    // Apply signed notation if requested
    if (isSigned)
    {
        if (n < 0)
        {
            *--p = '-';
        }
        else if (n > 0)
        {
            *--p = '+';
        }
        else
        {
            *--p = ' ';
        }
    }

    // Print the string right-justified
    count = numDigits;
    while (count--)
    {
        *ptr++ = *p++;
    }
    return;
}

答案 6 :(得分:0)

使用零作为单个数字值实例的填充字符输出日期和时间的另一个示例: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;
}
相关问题