Thursday, May 12, 2011

Push and Pop Stream state in C++

I often find iostreams in C++ a little confusing. I sometimes find myself falling back on C-style printfs, but from now on I'm trying to do formatted text 'The Right Way' in C++. I've written some code to allow myself to write my code like this (the stack.push/pop are my contribution):

  cout << stack.push << fixed << setprecision(1) << x << stack.pop << endl;

Some manipulators (like setprecision()) are permanent, any change made will remain in place for the rest of the execution of the program. But I don't want to have to reset everything manually. So I wanted to be able to save the entire state of the format flags. So I added the stack.push and stack.pop manipulators to push the format flags and the precision, so that the manipulators are now effectively temporary.

NB: Does anyone have a different/better solution? I feel like I'm reinventing the wheel.

The code needed is at http://gist.github.com/968629 . You'll need to declare a variable called stack (or any other name you like) before you can use it.

   #include "FormatFlagStack.cpp"
   FormatFlagStack stack;
     cout << stack.push << fixed << setprecision(1) << x << stack.pop << endl;

1 comments:

  1. What I say is your code is correct & proper enough to solve the problem.So I suggest you to go with your code.

    ReplyDelete