C++ 使用cout<;时,如何用前导零填充int&书信电报;操作人员
我希望C++ 使用cout<;时,如何用前导零填充int&书信电报;操作人员,c++,formatting,cout,C++,Formatting,Cout,我希望cout输出一个带前导零的整数,因此值1将打印为001,值25打印为025。我怎样才能做到这一点呢?有以下几点 #include <iomanip> #include <iostream> int main() { std::cout << std::setfill('0') << std::setw(5) << 25; } 默认情况下,setfill设置为空格字符(')setw设置要打印的字段的宽度,就是这样 如果
cout
输出一个带前导零的整数,因此值1
将打印为001
,值25
打印为025
。我怎样才能做到这一点呢?有以下几点
#include <iomanip>
#include <iostream>
int main()
{
std::cout << std::setfill('0') << std::setw(5) << 25;
}
默认情况下,setfill
设置为空格字符('
)setw
设置要打印的字段的宽度,就是这样
如果您有兴趣了解如何格式化一般的输出流,我为另一个问题写了一个答案,希望它有用:
计算填充('0');
库特宽度(3);
cout实现这一点的另一种方法是使用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;
intdd=1,mm=9,yy=1;
chars[25];
sprintf(s,“%02d-%02d-%04d”,年月日);
cout我将使用以下函数。我不喜欢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;
}
定义hexchar(x)((x)和0x0F)>9?((x)+'A'-10):((x)+'0'))
typedef签名的long-long-Int64;
//仅适用于数字的特殊printf
//请参阅下面的格式信息。
//
//在给定的“基数”中打印数字“n”
//完全使用“numDigits”。
//如果签名标志“isSigned”为真,则打印+/-。
//使用“padchar”中指定的字符填充额外字符。
//
//示例:
//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;
如果(!pszBuffer)
{
返回;
}
char*p,buf[32];
无符号长x;
无符号字符计数;
//准备负数
如果(未签名&(n<0))
{
x=-n;
}
其他的
{
x=n;
}
//设置小字符串缓冲区
计数=(numDigits-1)-(isSigned?1:0);
p=buf+sizeof(buf);
*--p='\0';
//第一个数字的力计算
//(防止zero根本不打印!!!)
*--p=(char)hexchar(x%碱基);
x=x/基;
//计算剩余数字
而(计数--)
{
如果(x!=0)
{
//计算下一位数
*--p=(char)hexchar(x%碱基);
x/=基部;
}
其他的
{
//没有剩余的数字,请向外填充到所需的长度
*--p=padchar;
}
}
//如有要求,应用签名符号
如果(未签名)
{
if(n<0)
{
*--p='-';
}
否则,如果(n>0)
{
*--p='+';
}
其他的
{
*--p='';
}
}
//右对齐打印字符串
计数=numDigits;
而(计数--)
{
*ptr++=*p++;
}
返回;
}
输出日期和时间的另一个示例,使用零作为单位数值实例的填充字符: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;
}
#包括“stdafx.h”
#包括
#包括
#包括
使用名称空间std;
int main()
{
time_t=time(0);//立即获取时间
struct tm*now=localtime(&t);
cout.fill('0');
cout tm_year+1900)在C++20中,您可以执行以下操作:
std::cout but..如何将格式化输出写入字符串(char*或char[]
)不是直接控制台。实际上我正在编写一个返回格式化string@harsh使用std::StringStream执行此操作后别忘了恢复流格式,否则稍后您会感到意外。此答案为我指明了正确的方向,但可以改进。要实际使用此代码,您需要包含
和文件顶部的
,您需要使用名称空间std;
编写,但这是一种不好的做法,因此您应该在回答中的三个标识符前面加上std::
@shashwat,您可以使用以下代码-std::stringstream filename;filename.fill('0');filename.width(5);filenamebut..如何将格式化输出写入字符串(char*或char[]
),而不是直接写入控制台。实际上,我正在编写一个返回格式化输出的函数string@ShashwatTrPATI使用<代码> STD::StrugSuth。@ AraK,我认为这在Turbo C++中是不起作用的。我使用了<代码> SpReTFF(s),%022-%02D--%04D。年月日)其中s
是char*
和dd,mm,yy
是int
类型。这将根据变量中的值编写02-02-1999
格式。我知道这是一个古老的答案,但仍然需要指出的是,sprintf通常不应该太受信任,因为您不能指定使用snprintf往往更安全。使用streams而不是*printf()也更安全,因为编译器有机会在编译时检查参数的类型;AraK接受的答案是类型安全和“标准”C++,它不依赖于对全局命名空间产生毒害的头。答案是使用日期格式作为示例。但是注意,它使用异国时间格式作为例子,尽管它看起来与表面上的ISO88601相似()。如果我理解正确,目前没有一个编译器支持此功能?来源:@jlh,这是一个库,不是编译器功能,但您是对的:标准库实现还不支持std::format(C++20最近才发布).我知道libc++和微软都在使用它。恭喜你将你的库移植到了C++20中!你第一次使用它很多年了
#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;
}
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
#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;
}