Jump to content

setw vs width

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
4 replies to this topic

#1
kumamako

kumamako

    Newbie

  • Members
  • PipPip
  • 16 posts
what really is the difference between using setw function and width(). Are they the same thing? can someone give me an example of each please.

#2
ZekeDragon

ZekeDragon

    Writes binary right handed and hex left handed

  • Moderators
  • 2,103 posts
Uhh... are you referring to C++ character streams? Or is this some kind of GUI library you're talking about? Info man, info!

Anyway, the differences between using setw and width() in the C++ ostreams are marginal, nothing more than syntax as far as I know. The documentation goes so far to say that setw is nothing more than a call to the width() member.

The only real difference is with width() you don't have to include the iomanip lib, whereas if you use setw you must explicitly #include <iomanip>.

- Zeke

#3
MathX

MathX

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 4,001 posts
And what about between cout.precision() and setprecision()? Is that all the same too?

Interested in participating in community events?
Want to harness your programming skill and turn it into absolute prowess?
Come join our programming events!


#4
ZekeDragon

ZekeDragon

    Writes binary right handed and hex left handed

  • Moderators
  • 2,103 posts
I refer to these guys a lot.

The manipulator setprecision behaves as a call to the member function ios_base::precision(). Again, it seems the only real difference is preference and the need to include <iomanip>. However, a small difference I notice is with the "fixed" manipulator:
float f = 3.14159;

cout << setprecision(9) << f << endl; // prints "3.14159"

cout << fixed << setprecision(9) << f << endl; // prints "3.141590000"
Whereas with cout.precision() this would require two seperate function calls.
float f = 3.14159;

cout.precision(9);

cout << f << endl; // prints "3.14159"

cout.setf(ios::fixed, ios::floatfield); //when a float is provided, the precision is fixed.

cout << f << endl; // prints "3.141590000"
I'd use the manipulators from <iomanip> personally since they're a bit more self documenting and easier, at least for me, to read. The differences are marginal though.

- Zeke

#5
MathX

MathX

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 4,001 posts
Thanx m8 :)

Interested in participating in community events?
Want to harness your programming skill and turn it into absolute prowess?
Come join our programming events!