Mar 16, 2019 at 7:48pm UTC
Text makes cout forget settings?
1 2 3 4 5 6 7 8 9
#include <iostream>
#include <string>
int main()
{
std::cout.fill('0' );
std::cout.width(4);
std::cout << std::hex << 100;
}
shows as expected:
In contrast
1 2 3 4 5 6 7 8 9
#include <iostream>
#include <string>
int main()
{
std::cout.fill('0' );
std::cout.width(4);
std::cout << "Test: " << std::hex << 100;
}
shows -- unexpected:
Neither the Tutorials nor the Reference of this site helped me to get also in the second case the leading zeros. What do I wrong?
Last edited on Mar 16, 2019 at 7:56pm UTC
Mar 16, 2019 at 7:50pm UTC
Setting the width only affects the next output.
Mar 16, 2019 at 8:01pm UTC
Use
std::setw()
from
<iomanip>
.
1 2 3 4 5 6 7 8 9
#include <iostream>
#include <iomanip>
int main()
{
std::cout.fill('0' );
std::cout << "Test: " << std::hex << std::setw(4) << 100 << '\n' ;
}
You can also chain the fill character with
std::setfill()
. Also part of
<iomanip>
.
1 2 3 4 5 6 7
#include <iostream>
#include <iomanip>
int main()
{
std::cout << "Test: " << std::hex << std::setfill('0' ) << std::setw(4) << 100 << '\n' ;
}
Suggestion: only add the headers you need to compile the current code. Unneeded headers are just a waste of keystrokes.
Last edited on Mar 16, 2019 at 8:05pm UTC
Mar 16, 2019 at 9:57pm UTC
And yet it ended up costing extra keystrokes for FurryGuy, you and me!