HageNezz
HageNezz

Reputation: 57

Ignore certain inputs in a line of inputs

I am making a function that only accepts pair of integer inputs. This will be repeated in the while loop until the user input " -5 -5". If I input "5 7 -4 3 10 1 -2 0 -5 -5", it will take all of them as valid inputs. And if there are characters in the input like "e p 5 7 -4 3 10 1 -2 0 -5 -5", my code will ignore the entire inputs of "e p 5 7 -4 3 10 1 -2 0 -5 -5". Instead, I just want to skip the first pair "e p" and still keep the rest.

What about this, "e p erewr djfe -4 3 ekjea 23 -2 0 -5 -5"? In this case, I only want " -4 3 -2 0 -5 -5". How can I accomplish this? Thank you.

Here is my code:

int input1 = 0;
int input2 = 0;
do {
    cin >> input1 >> input2;
    if (cin.fail()) {   // This will handle non-int cases
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
    } else {
        setValues(input1, input2);
    }
} while((input1 != -5 && input2 != -5));

Upvotes: 1

Views: 57

Answers (1)

Domenico Lanza
Domenico Lanza

Reputation: 168

I propose this solution without the cin.fail(), but using strings,stoi and try catch blocks.

#include <iostream>
#include <limits>
#include <string>
using namespace std;

int main()
{
    string input1;
    string input2;
    int in1,in2;
    bool ok=false;
    bool ok2=false;
    bool ignore=false;
    do
    {
        ok=false;
        cin>>input1;
        try
        {
            in1=stoi(input1);
            ok=true;
        }
        catch(...)
        {

        }
        cin>>input2;
        ok2=false;
        if(ok)
        {
            try
            {
                in2=stoi(input2);
                ok2=true;
            }
            catch(...)
            {

            }
            if(ok2) 
                setValues(in1,in2);
        }
    }
    while((in1 != -5 && in2 != -5));
}

Upvotes: 1

Related Questions