funny-looking while loop
This is from Prata, C++ Primer Plus, 5th ed., p. 588.
He's showing here how to implement a user-defined class "String", which is supposed to be a functional but oversimplified version of the library string class. The private static const int CINLIM has been set to 80 in the header file. Here's Prata's implementation of >>, where the part I would definitely not thought of putting in is the while loop:
Ok, so the while loop runs if
istream & operator>>(istream & is, String & st)
st = temp;
while (is && is.get() != '\n')
1) The input operation defined by "is" is successful, and
2) The value of is.get() is not the newline character.
On this implementation, if "is" fails, then >> just returns the failed "is" and the String st doesn't undergo any changes.
And if "is" succeeds, then the String st gets set to the value entered, and then we get to the while loop. is.get() should have the value '\n' as long as the input didn't exceed 80 characters (right?), so the loop won't run in this case.
But if "is" is cin, for example, and the user entered 120 characters before pressing enter, then cin.get() is going to have the value of some junk character (not captured in st or temp), and the loop should move the input location up to the point where '\n' was entered (?). So, is the function of this while loop just to clear out the junk characters from is.get()?
If so, couldn't he just have substituted is.clear(); for the whole while loop? I'm assuming that if get() is a member function of all istream objects, then clear() also is.
Sorry, with regard to my last question, I just thought of the case of an input file, call it inFile, where inFile.clear() doesn't make much sense.
So the remaining question is just whether I've understood correctly why he puts this loop there in the first place.
You understand it correctly.