13.6.3. Field Width (width, setw)

The width member function (of base class ios_base) sets the field width (i.e., the number of character positions in which a value should be output or the maximum number of characters that should be input) and returns the previous width. If values output are narrower than the field width, fill characters are inserted as padding. A value wider than the designated width will not be truncated—the full number will be printed. The width function with no argument returns the current setting.


Image Common Programming Error 13.1

The width setting applies only for the next insertion or extraction (i.e., the width setting is not sticky); afterward, the width is set implicitly to 0 (that is, input and output will be performed with default settings). Assuming that the width setting applies to all subsequent outputs is a logic error.



Image Common Programming Error 13.2

When a field is not sufficiently wide to handle outputs, the outputs print as wide as necessary, which can yield confusing outputs.


Figure 13.10 demonstrates the use of the width member function on both input and output. On input into a char array, a maximum of one fewer characters than the width will be read, because provision is made for the null character to be placed in the input string. Remember that stream extraction terminates when nonleading white space is encountered. The setw stream manipulator also may be used to set the field width. [Note: When prompted for input in Fig. 13.10, the user should enter a line of text and press Enter followed by end-of-file (<Ctrl> z on Microsoft Windows systems and <Ctrl> d on Linux and OS X systems).]


 1   // Fig. 13.10: fig13_10.cpp
 2   // width member function of class ios_base.
 3   #include <iostream>
 4   using namespace std;
 5
 6   int main()
 7   {
 8      int widthValue = 4;
 9      char sentence[ 10 ];
10
11      cout << "Enter a sentence:" << endl;
12      cin.width( 5 ); // input only 5 characters from sentence
13
14      // set field width, then display characters based on that width
15      while ( cin >> sentence )
16      {
17         cout.width( widthValue++ );
18         cout << sentence << endl;
19         cin.width( 5 ); // input 5 more characters from sentence
20      } // end while
21   } // end main


Enter a sentence:
This is a test of the width member function
This
   is
     a
   test
      of
      the
      widt
          h
        memb
           er
          func
           tion


Fig. 13.10. width member function of class ios_base.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.14.98