我想让cout输出一个前导为零的int,因此1将被打印为001,25将被打印为025。我该怎么做呢?
当前回答
在单个数字值的实例上使用零作为填充字符输出日期和时间的另一个示例: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;
}
其他回答
在c++ 20中,你可以做到:
std::cout << std::format("{:03}", 25); // prints 025
在此期间,您可以使用{fmt}库,std::format是基于。
免责声明:我是{fmt}和c++ 20 std::format的作者。
下面,
#include <iomanip>
#include <iostream>
int main()
{
std::cout << std::setfill('0') << std::setw(5) << 25;
}
输出将是
00025
Setfill默认设置为空格字符(' ')。Setw设置要打印的字段的宽度,仅此而已。
如果你有兴趣了解如何格式化输出流,我写了另一个问题的答案,希望它是有用的: 格式化c++控制台输出。
cout.fill( '0' );
cout.width( 3 );
cout << value;
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
在单个数字值的实例上使用零作为填充字符输出日期和时间的另一个示例: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;
}