![]() |
| | #1 |
| Registered User Join Date: May 2009
Posts: 165
| funny-looking while loop 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: Code: istream & operator>>(istream & is, String & st)
{
char temp[String::CINLIM];
is.get(temp, String::CINLIM);
if (is)
st = temp;
while (is && is.get() != '\n')
continue;
return is;
}
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. |
| Aisthesis is offline | |
| | #2 |
| Registered User Join Date: May 2009
Posts: 165
| 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. |
| Aisthesis is offline | |
| | #3 |
| Registered User Join Date: Jan 2005
Posts: 7,252
| You understand it correctly. |
| Daved is offline | |
| | #4 |
| Registered User Join Date: May 2009
Posts: 165
| tx again, Dave! |
| Aisthesis is offline | |
![]() |
| Thread Tools | |
| Display Modes | |
|
Similar Threads | ||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| nested loop, simple but i'm missing it | big_brother | C Programming | 19 | 10-23-2006 10:21 PM |
| While loop misbehaving (or misunderstanding) | mattAU | C Programming | 2 | 08-28-2006 02:14 AM |
| loop in a linked linked lists | kris.c | C Programming | 6 | 08-26-2006 12:38 PM |
| while loop help | bliznags | C Programming | 5 | 03-20-2005 12:30 AM |
| loop issues | kristy | C Programming | 3 | 03-05-2005 09:14 AM |