2013-07-09 10 views
10

ho trovato questa domanda già chiesto, ma la risposta a tutti dà ècorrettamente pad interi negativi con zeri con std :: cout

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

che va bene per i numeri positivi, ma con -5, stampa:

000-5 

C'è un modo per farlo stampare -0005 o forzare cout per stampare sempre almeno 5 cifre (che risulterebbe in -00005) come possiamo fare con printf?

risposta

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

uscita:

-0005 

std::internal

Edit:

Per coloro coloro che si occupano di queste cose, 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

Funziona, grazie! – Philippe

+0

Sei il benvenuto! Questa domanda è andata bene e rapidamente. Spero che questo aiuti anche gli altri. – BoBTFish