How to loop back if incorrect input put in

I am wanting to loop back to the question asking "Would you like to Play again, y/n." once a incorrect input is put in such as if h is put in instead of y/n then it will state that it is incorrect input, please try again. so far I have had no luck in doing so.
Here is the code for it:

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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
while (1)
	{
		b++;
		Input();
		Display();
		//if player wins/tie function
		//if X (Player 1) wins
		if (Win() == 'X')
		{
			system("cls");
			cout << X << " has Won!" << endl;
			cout << "Would you like to Play again, y/n." << endl;
			cin >> choice2;
			if (choice2 == "y" || choice2 == "Y")
			{
				break;
				resetGrid();
				Display();
			}
			else if (choice2 == "n" || choice2 == "N")
			{
				return 0;
			}
			else
			{
				cout << "That is not the correct input, please try again: ";
				cin >> choice2;
			}
		}
		//if O (Player 2) wins
		else if (Win() == 'O')
		{
			system("cls");
			cout << O << " has Won!" << endl;
			cout << "Would you like to Play again, y/n." << endl;
			cin >> choice2;
			if (choice2 == "y" || choice2 == "Y")
			{
				break;
				resetGrid();
				Display();
			}
			else if (choice2 == "N" || choice2 == "n")
			{
				return 0;
			}
			else
			{
				cout << "That is not the correct input, please try again: ";
				cin >> choice2;
			}
		}
		//if players tie
		else if (Win() == '/' && b == 9)
		{
			system("cls");
			cout << "It's a Tie!" << endl;
			cout << "Would you like to Play again, y/n." << endl;
			cin >> choice2;
			if (choice2 == "y" || choice2 == "Y")
			{
				break;
				resetGrid();
				Display();
			}
			else if (choice2 == "N" || choice2 == "n")
			{
					return 0;

			}
			else
			{
				cout << "That is not the correct input, please try again: ";
				cin >> choice2;
			}
		}
Have you noticed that you're doing exactly the same thing 3 times? That's a good indication you should be using a function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
bool play_again ()
{   char choice2;

    cout << "Would you like to Play again, y/n." << endl;
    while (true)
    {   cin >> choice2;
	    if (choice2 == "y" || choice2 == "Y")
	    {   resetGrid();
	        Display();
	        return true; 
	    }
        if (choice2 == "N" || choice2 == "n")
	        return false; 		
	    cout << "That is not the correct input, please try again: ";
		cin >> choice2;
	}
}
...
    if (! play_again())
    	return 0;


Last edited on
Yes this works much better, tyvm.

But with me doing this I now have another problem where when I have chosen to play again and entered a position to place X in it simply does nothing and when I do it again it comes up with incorrect input and posts the play again function, idk why it is doing this..
Topic archived. No new replies allowed.