development

cout << 연산자를 사용할 때 선행 0으로 int를 채우려면 어떻게해야합니까?

big-blog 2020. 4. 16. 08:21
반응형

cout << 연산자를 사용할 때 선행 0으로 int를 채우려면 어떻게해야합니까?


cout선행 0으로 int를 출력 하려고 하므로 값 1이로 인쇄되고 001값이로 25인쇄됩니다 025. 어떻게해야합니까?


다음과 같이

#include <iomanip>
#include <iostream>

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

출력은

00025

setfill' '기본적으로 공백 문자 ( )로 설정됩니다. setw인쇄 할 필드의 너비를 설정합니다.


일반적으로 출력 스트림을 형식화하는 방법을 알고 싶다면 다른 질문에 대한 답변을 썼습니다 .C ++ 콘솔 출력 형식화 가 도움이되기를 바랍니다 .


이것을 달성하는 또 다른 방법 printf()은 C 언어의 오래된 기능을 사용하는 것입니다.

이처럼 사용할 수 있습니다

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. 이렇게하면 패드가 설정 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

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

다음 기능을 사용합니다. 나는 싫어 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;
}

단일 숫자 값의 인스턴스에서 채우기 문자로 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;
}

참고 URL : https://stackoverflow.com/questions/1714515/how-can-i-pad-an-int-with-leading-zeros-when-using-cout-operator

반응형