CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2

Thread: width()

  1. #1
    Join Date
    Jul 2009


    hello. This the program from the book. I am having a hard time understanding the code. I looked at the program output and tried to see what it is doing but no luck. can someone explain me what this program does.

    #include <iostream>
    using std::cin;
    using std::cout;
    using std::endl;

    int main()
    int widthValue = 4;
    char sentence[ 10 ];

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

    while ( cin >> sentence )
    cout.width( widthValue++ );
    cout << sentence << endl;
    cin.width( 5 ); // input 5 more characters from sentence
    return 0;

  2. #2
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Seattle, WA

    Re: width()

    According to the documentation, istream::width restricts how many characters can be read from the stream. In this case, you're never allowing more than 4 characters (plus a terminating NULL) to be written into "sentence" on the while line.

    This is fine, since sentence is 10 large. In fact, the width used could be anything up to 10. The important thing is that you don't want it to be possible for cin to attempt to write 20 characters into a 10 character array.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Windows Mobile Development Center

Click Here to Expand Forum to Full Width

On-Demand Webinars (sponsored)