質問: cout <<演算子を使用する場合、intの先頭にゼロを埋め込むにはどうすればよいですか? coutに先行ゼロ付きのintを出力させたいので、値1は001として出力され、値25は025として出力されます。これどうやってするの?
回答: 次の関数を使用します。 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; }