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;
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.
Bookmarks