C++ 使用 cout << 运算符时,如何用前导零填充 int?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1714515/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 20:59:07  来源:igfitidea点击:

How can I pad an int with leading zeros when using cout << operator?

c++formattingcout

提问by jamieQ

I want coutto output an int with leading zeros, so the value 1would be printed as 001and the value 25printed as 025. How can I do this?

我想cout,以输出带前导零一个int,因此该值1将被打印成001和值25打印为025。我怎样才能做到这一点?

回答by AraK

With the following,

有了以下,

#include <iomanip>
#include <iostream>

int main()
{
    std::cout << std::setfill('0') << std::setw(5) << 25;
}

the output will be

输出将是

00025

setfillis set to the space character (' ') by default. setwsets the width of the field to be printed, and that's it.

setfill' '默认设置为空格字符 ( )。setw设置要打印的字段的宽度,就是这样。



If you are interested in knowing how the to format output streams in general, I wrote an answer for another question, hope it is useful: Formatting C++ Console Output.

如果您有兴趣了解一般如何格式化输出流,我为另一个问题写了一个答案,希望它有用: 格式化 C++ 控制台输出。

回答by shashwat

Another way to achieve this is using old printf()function of C language

实现此目的的另一种方法是使用printf()C 语言的旧功能

You can use this like

你可以像这样使用

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

This will print 09 - 01 - 0001on the console.

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

You can also use another function sprintf()to write formatted output to a string like below:

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

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

Don't forget to include stdio.hheader file in your program for both of these functions

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

Thing to be noted:

需要注意的事项:

You can fill blank space either by 0 or by another char (not number).
If you do write something like %24dformat specifier than this will not fill 2in blank spaces. This will set pad to 24and will fill blank spaces.

您可以用 0 或另一个字符(不是数字)填充空格。
如果您确实编写了%24d格式说明符之类的内容,则不会填充2空格。这将设置 pad24并填充空格。

回答by quest333

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

This produces the output:

这会产生输出:

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

回答by lyricat

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

回答by Thomas J Younsi

I would use the following function. I don't like sprintf; it doesn't do what I want!!

我会使用以下功能。我不喜欢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 = '
#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;
}
'; // 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; }

回答by user8163172

Another example to output date and time using zero as a fill character on instances of single digit values: 2017-06-04 18:13:02

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

##代码##