Wednesday, July 17, 2013

Printing an int in C++

Q: How do you print an integer to standard output in C++?

A: Like this!

printf("%d", x);

Q: Please use C++ facilities.

A: Sure.

std::cout << x;

Q: But what if someone switched the stream to hex mode before calling your code?

std::cout << std::hex;

Then your code will print "a" instead of "10", which is not what you want.

A: Okay, I'll switch the stream to decimal mode, just to be sure:

std::cout << std::dec << x;

Q: Now your code has an unintended side effect, it might change the state of the stream for the next caller.

A: Hmm. So I need to restore the stream to its previous state, whatever it was? Hang on, I'll check the internet...

(a minute later)

Wow. There's a Boost library to do that.

Q: Seriously?

A: You know what, I'd like to go back to my first answer with printf.

2 comments:

  1. Nice! :) std::iostream is a great example of how you should not design IO stream library. Java and C# got that much better.

    ReplyDelete
  2. cout is a global stream object. If you modify any objects state, the modifications don't magically change when you want them to. For e.g. if you create a file object and are writing in append mode, its not going to change state in the middle. Thats such an obvious thing.

    If you want to use a printing system not based on C++ I/O streams, you can do that too. The language is not stopping you.

    ReplyDelete