Forcing the extraction operator to ignore certain input

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • alw0015
    New Member
    • Oct 2006
    • 1

    Forcing the extraction operator to ignore certain input

    I'm working on a piece of code that reads in a time from the user.

    This time value consists of 3 separate inputs:

    1 integer representing hours
    1 char representing the ":"
    1 integer representing minutes

    for example:

    cout << "Time: " <<;
    cin >> x1 >> ch1 >> y1;

    "the user would input 8:35 for example and it would be stored as
    x1 = 8
    ch1 = :
    y1 = 35

    Now, my problem is that I need to account for the fact that the user may input a bunch of junk AFTER I've got all the data I need.

    For example, they might input:

    "8:35 this is the time"

    And I need it to ignore anything past 8:35, so essentially, anything past the y1 variable must be ignored.

    I've been messing around with cin.ignore but haven't found a way to get it to ignore things after a certain series of inputs. Is it even possible to use cin.ignore in this situation?

    I'm new to the C++ scene and need a simple, understandable solution.
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    use getline to read the entire line of input into a string. Then from that string create a stringstream to read the bits you are interested in. You can just discard the rest, the input will be cleared because you have read it all.

    Comment

    Working...