Populating multiple variables with one cin

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;
  char colon;  
  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;
    break;
  


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?

Thanks in advance,
Ken Long
Albuquerque
Last edited on
This line:
cin >> hr >> colon >> min >> colon >> sec;
behaves just the same as this:
1
2
3
4
5
cin >> hr;
cin >> colon;
cin >> min;
cin >> colon;
cin >> sec;

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.
Last edited on
she used throw away variable because you can't use it on time calculation, wasn't she?
Thank you Chervil for the explanation. That helped a lot.

If I understand you correctly, the var colon is necessary so cin can discard the colons in the input string.

This allows the user to input the time in a format that's recognizable to her.

Those colons and the var "colon" are never used in the rest of the program. That leaves just the hours, minutes, and seconds in separate variables so the time calculations can be done.

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.
Topic archived. No new replies allowed.