2013-07-09 15 views
10

Znalazłem to pytanie już poproszony, ale każdy daje odpowiedź jestPrawidłowo pad ujemne liczby całkowite z zer z std :: cout

std::cout << std::setw(5) << std::setfill('0') << value << std::endl; 

co jest w porządku dla liczb dodatnich, ale -5, drukuje:

000-5 

Czy istnieje sposób, aby wydrukować -0005 lub zmusić cout zawsze wydrukować co najmniej 5 cyfr (co skutkowałoby -00005), jak możemy zrobić z printf?

Odpowiedz

15
std::cout << std::setw(5) << std::setfill('0') << std::internal << -5 << '\n'; 
//              ^^^^^^^^ 

wyjściowa:

-0005 

std::internal

Edit:

Dla tych osób, które dbają o takich rzeczach, N3337 (~c++11) 22.4.2.2.2:

The location of any padding is determined according to Table 91. 
        Table 91 - Fill padding 
State        Location 
adjustfield == ios_base::left  pad after 
adjustfield == ios_base::right  pad before 
adjustfield == internal and a 
sign occurs in the representation pad after the sign 
adjustfield == internal and 
representation after stage 1 began 
with 0x or 0X      pad after x or X 
otherwise       pad before 
+0

Działa, dzięki! – Philippe

+0

Serdecznie witamy! To pytanie poszło dobrze i szybko. Mam nadzieję, że to pomaga także innym ludziom. – BoBTFish

Powiązane problemy