How to clear the input stream when given two inputs

When I enter 2 letters (such as b c) as the coordinates to check if the program outputs an error message, for some reason, it outputs two error messages instead of just one error message. However, it doesn't do this when I enter a letter and a number (such as b 1), so I think its checking cin.fail() for each input individually instead of checking cin.fail() for both inputs at once maybe? I'm not sure how to fix this issue.

This is the function where I ask for two integer inputs from the user (coordinates) and I have to ensure that there is an error message if the user enters non integer values.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
int inrow = 0; 
int incol = 0; 
    cout << person1->getName() << " (X) " << "Mark Location: ";
    cin >> inrow >> incol;
    
    //ensure that the user cannot enter non-int values since the input is taking 
     in integer values
    if (cin.fail())
    {
        cin.clear();
        cin.ignore();
        cout << "Invalid. Please enter coordinates as numbers." << endl;
        moveX();
    }


This is my output when I enter a b into the program:
[/code]
Rin (X) Mark Location: a b
Invalid. Please enter coordinates as numbers.

Rin (X) Mark Location: Invalid. Please enter coordinates as numbers.

Rin (X) Mark Location:
[/code]
Here you can see it outputs the error message twice before asking for a new input.

This is my output when I enter a 1 into the program:
[/code]

Rin (X) Mark Location: a 1
Invalid. Please enter coordinates as numbers.

Rin (X) Mark Location:
[/code]
Here it only outputs the error message once before asking for a new input.

I'm not sure how to resolve this. Any help would be greatly appreciated!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <utility>
#include <string>
#include <regex>

std::pair<int,int> get_location()
{
    std::cout << "enter row col: "  ;

     // regex: beginning of string, zero or more ws, 1 to 3 decimal digits (capture), one or more ws,
     // 1 to 3 decimal digits (capture), zero or more ws, end of string
     static const std::regex row_col_re( "^\\s*(\\d{1,3})\\s+(\\d{1,3})\\s*$" ) ;
     std::smatch match ;
     std::string line ;
     if( std::getline( std::cin, line ) && std::regex_match( line, match, row_col_re ) )
         return { std::stoi( match[1] ), std::stoi( match[2] ) } ;

     std::cout << "invalid input. try again\n" ;
     return get_location() ;
}

int main()
{
   const auto [ row, col ] = get_location() ;
   std::cout << "row,col: " << row << ',' << col << '\n' ;
}
Topic archived. No new replies allowed.