-
August 3rd, 2009, 02:43 PM
#1
width()
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.
CODE
#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;
-
August 3rd, 2009, 03:43 PM
#2
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
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|