No leading zeros?

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:
0064

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:
Test: 64

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
Setting the width only affects the next output.
closed account (E0p9LyTq)
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
1
2
3
4
5
6
7
8
9
10
#include <iostream>
#include <string>

int main()
{
  	std::cout.fill('0');
	std::cout << "Test: ";
	std::cout.width(4);
	std::cout << std::hex << 100;
}

Test: 0064

Solved -- thank you.
Suggestion: only add the headers you need to compile the current code. Unneeded headers are just a waste of keystrokes.

I started a new tab in the browser, set URL http://cpp.sh/ and replaced the content of int main() -- so deleting unnecessary #include <string> would have been more keystrokes for me.
And yet it ended up costing extra keystrokes for FurryGuy, you and me!
Topic archived. No new replies allowed.