Hi, I'm in the 4th week as a new student in C++ at Central New Mexico Community College. We were shown a code snippet yesterday that the teacher was unable to explain. She went through the mechanics of it, but many of us were left wondering "why." The book author used a "throw-away" variable (colon) in a cin statement like this:
1 2 3 4 5 6 7 8 9
int hr, min, sec, totalsec;
case 1: // Convert H:M:S to seconds
cout << "\n Enter H:M:S format, i.e. 3:26:33 ==> ";
cin >> hr >> colon >> min >> colon >> sec;
totalsec = hr*3600 + min*60 + sec;
cout << " Result: " << totalsec;
Because of the throw-away variable, the cin was able to grab the proper part of the input string and populate the proper variables. Can anyone explain how this works?
The other point is that when fetching an integer from the stream, like this cin >> hr, the process stops as soon as it detects a character which is not a valid part of an integer. So when the first ':' character is detected, the value of hr is complete. The remaining characters (including the ':') are left in the input buffer.
Then cin >> colon will extract just one non-whitespace character, which would be the ':', though it doesn't inspect the contents to see what is in there.
After that, the next available character in the buffer is the start of the value for min, and so on.
Yes, I think that's a fair way of looking at it. You might say, if all we are going to do is to discard the colons, then why bother getting the user to type them. But it is indeed to do with the format being familiar and easily understood by the user.