A more efficient way of doing this? (Play Again Loops)

Hello everyone. For my first post here, let me explain a bit about what I learned so far and am trying to do.

I've been reading C++ "tutorials" and a beginners book for the past 3 days. So far, I have had variables, types, basic I/O, while loops, do loops, if/else/elseif and switch statements taught to me thus far.

Anyway, my goal is game programming in the future, which brings me to my question here. What I am trying to do is make a simple (very very simple) "Do you want to play again?" program. Unlike what some books and tutorials teach, I am trying to make it so if you type anything other than y or n, it will output "Invalid choice, please try again." and have you keep trying until y or n is inputted. After about an hour of trial and error I got it to work! (I was really dedicated :P) However, I am sure there is a more efficient way of doing it. Can someone look at my code and give me suggestions of a more efficient way of doing it, or is it good enough as is? Thank you.

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
// Play Again Test

#include <iostream>
using namespace std;

void yesOrNo()
{
	cout << "You played a game.\n";
	cout << "Do you want to play again? (y/n): ";
}

int main()
{
	char choice;

	do {
		yesOrNo();
		cin >> choice;
	} while (choice == 'y');

	do {
		cout << "Invalid choice, please try again!\n";
		yesOrNo();
		cin >> choice;
	} while (choice != 'n');

	cout << "Okay, good bye!\n";

	system("PAUSE");

	return 0;
}
I'd be tempted to do it like this:

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
#include <iostream>

int main( int argc, char* argv[] )
{
  bool running = true;
  char input;

  while( running )
  {
    std::cout << "You played a game. Do you want to play again? (Y/N): ";

    while( !( std::cin >> input ) || 
          ( tolower( input ) != 'y' && tolower( input ) != 'n' ) )
    {
      std::cout << "Invalid choice, try again: ";
      std::cin.ignore( 256, '\n' );
      std::cin.clear();
    }

    if( tolower( input ) == 'n' ) 
      running = false;
  }

  std::cout << "Goodbye\n";

  return 0;
}
Hi WaRori,

Have a look at this :

http://www.cplusplus.com/forum/beginner/104553/2/#msg564228


Hope all goes well
Topic archived. No new replies allowed.