Q:

C++'s cin.width function explanation

I've read this passage in the book(which barely explained) a dozen times but can't understand how this is really working. I'm trying to figure out how the functions are working.
int main() {
     int widthValue = 4;
     char sentence[ 10 ];

     cout << "Enter a sentence:" << endl;
     cin.width( 5 ); // input only 4 characters from sentence

     // set field width, then display characters based on that width
     while ( cin >> sentence )
     {
      cout.width( widthValue++ );
      cout << sentence << endl;
      cin.width(5); // input 5 more characters from sentence
      } // end while
      return 0;
 } // end main

Now the following output is produced, and here's my trouble. The first line says cin.width, and this line means that the first 4 characters, actually, will be read - namely, "This", but then you output a field width of 4, so when you execute the 'cout << sentence << endl statement you print 4 characters, namely - "This". After, you read 5 more characters from sentence. But I get lost on the next iteration of the loop because the width then becomes 5, yet you output "   is". I don't get the concept.

A:

When you set width(w) on cin and then read a C string from it, operator >> stops when one of the following happens:

w-1 characters have been read - >> needs one more character for null terminator, which is included in the count
a delimiter character is reached - in your case, whitespace is the delimiter
End of input is reached - There's nothing >> can do when there's no more data to read.

Therefore, your loop partitions the input as follows:

If a word is shorter than four characters in length, it would be read in its entirety
Otherwise, the word would be read in four-character increments; the last part may have fewer than four characters.

Printing is right-justified, with spaces pre-pended to each word or a portion of the word that was previously read from cin. The widthValue++ expression controls the overall width, so each next word gets one extra space in front of it.
Here is the output for "jackdaws love my big sphinx of quartz", with | marks added to show the beginning and the end of each line:
|jack|
| daws|
|  love|
|     my|
|     big|
|     sphi|
|        nx|
|         of|
|        quar|
|           tz|

