2009-11-11 185 views
185

我希望cout输出一个带前导零的int,所以1的值将被打印为001,并且值25的值被打印为025 ..你明白了..我该怎么做?如何在使用cout <<运算符时使用前导零填充int?

谢谢。

+1

可能出现[用C++输出运算符打印前导零(printf等价物)?](http://stackoverflow.com/questions/530614/prin t-leading-with-c-output-operator-printf-equivalent) – atoMerz

回答

276

首先包括<iomanip>,则:

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

output: 
00025 

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


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

+3

但是..我怎么能写格式化输出到字符串('char *或char []')而不是直接控制台。其实我正在写一个函数,返回格式化的字符串 – shashwat

+8

@harsh使用std :: stringstream – cheshirekow

+7

不要忘记恢复流格式后,你会得到一个讨厌的惊喜后。 –

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

但是..我怎么能写格式化输出到一个字符串('char *或char []')不是直接控制台。其实我正在写一个函数,返回格式化的字符串 – shashwat

+1

@Shashwat Tripathi使用'std :: stringstream'。 – AraK

+0

@AraK 我认为这不适用于Turbo C++。我用'sprintf(s,“%02d-%02d-%04d”,dd,mm,yy);''where's'是'char *','dd,mm,yy'是'int'类型。这将根据变量中的值写入'02-02-1999'格式。 – shashwat

32

另一种方式来实现这一目标是使用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或其他填充空格char(不是数字)。
如果您确实写了类似%24d格式的说明符,则不会在空格中填写2。这会将垫设置为24并填充空白区域。

+5

我知道这是一个旧的答案,但仍然应该指出,sprintf通常不应该太信任,因为您无法指定它应该写入的缓冲区的长度。使用snprintf往往更安全。使用流而不是* printf()也是更安全的类型,因为编译器有机会在编译时检查参数的类型; AraK公认的答案既是类型安全又是“标准”的C++,并且不依赖于中毒全局名称空间的头文件。 – Magnus

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); --> "0" 
// 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; 
    } 

    // setup little 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; 
} 
23
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 
0

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