Basic cin - testing for extra unwanted input

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • hokasu
    New Member
    • Oct 2008
    • 1

    Basic cin - testing for extra unwanted input

    In the following example, I want the user to input something like:
    1 + 2 = 3, then (not included) test its validity.

    string op, eq;
    int num1, num2, user_result;
    cout<<"Please key in your equation.";
    cin >> num1>>op>>num2> >eq>>user_resul t;

    However, I need to "invalid input" this kind of input:
    1 + 2 = 3 + 0

    I can't think how to test for the extra bit. I tried an additional variable then checking if it was nul, but obviously, the program waits for the extra input.
    Is there a way to check if there is extra input? I thought of getline(cin, s) or something, but thats for strings.
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    When you use cin >>, you are using formatted input. That is, you know ahead of time what type of data is coming in. That means 1 + 2 = 3 + 0 won't happen.

    If you don't know that, then don't use the >> operator. Instead, use cin.get and parse the input a character at a time.

    Comment

    Working...