سؤال

Could anyone explain me the declaration of the setw manipulator? I was completely blown off trying to understand it.! The declaration of the setw in iomanip is as follows

 smanip setw(int)

now what is smanip? what happens when we give std::cout << setw(10) << "Hai" [ i want to know how the output is actually affected by setw, in other words the actions happening under the hood)

هل كانت مفيدة؟

المحلول

smanip is an implementation-defined type. The library can define or typedef it to anything it likes, as long as the job gets done.

In practice, it will be some kind of structure representing (a) the manipulation to be performed, and (b) the argument 10 to be used in this manipulation. It might also have a function to perform the manipulation, or it might not, depending how the implementation has defined operator<<(ostream &, smanip), or some similar overload to catch the necessary operand types. I haven't checked my implementation to find out.

As for how the output is affected: my_stream << setw(10) is defined to have the same effect on the stream as calling my_stream.width(10). So the operator<< overload will ensure that happens in some implementation-specific way. The operator overload for non-parameterized stream manipulators is defined specifically to call the manipulator, but with smanip there's a little more freedom for implementations.

نصائح أخرى

setw(int) by itself doesn't modify anything. It simply returns a stream manipulator (smanip) that can be used to modify the stream's behaviour.

// setw example
#include <iostream>
#include <iomanip>
using namespace std;

int main () {
  cout << setw (10);
  cout << 77 << endl;
  return 0;
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top