Imprimir ceros a la izquierda con el operador de salida C++?
¿Cómo puedo formatear mi salida en C++? En otras palabras, ¿cuál es el C++ equivalente al uso de printf
de esta manera:
printf("%05d", zipCode);
Sé que podría usar printf
en C++, pero preferiría el operador de salida <<
.
¿Solo usarías lo siguiente?
std::cout << "ZIP code: " << sprintf("%05d", zipCode) << std::endl;
48
4 answers
Esto hará el truco:
#include <iostream>
#include <iomanip>
using namespace std;
cout << setw(5) << setfill('0') << zipCode << endl;
// or use this if you don't like 'using namespace std;'
std::cout << std::setw(5) << std::setfill('0') << zipCode << std::endl;
Los manipuladores IO más comunes que controlan el relleno son:
-
std::setw(width)
establece el ancho del campo. -
std::setfill(fillchar)
establece el carácter de relleno. -
std::setiosflags(align)
establece la alineación, donde align es ios::left o ios::right.
76
Author: paxdiablo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-04-22 10:16:57
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-04-22 10:16:57
Utilice las llamadas setw y setfill :
std::cout << std::setw(5) << std::setfill('0') << zipCode << std::endl;
8
Author: Nik Reiman,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-02-10 02:20:08
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-02-10 02:20:08
cout << setw(4) << setfill('0') << n << endl;
De:
4
Author: anthony,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-02-10 00:03:27
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-02-10 00:03:27
O
char t[32];
sprintf_s(t, "%05d", 1);
Producirá 00001 como el OP ya quería hacer
0
Author: Jason Newland,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-08-13 11:42:29
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-08-13 11:42:29