I've dabbled in a bit of C and C++ over the years but now i want to learn more. So the best way in my opinion to really get to grips with them is to jump right in and attempt to write a program, learning as i go along. Anyway, for my first c/c++ app in a while i've decided to write a command-line 5x5 grid tic-tac-toe game. Anyway a problem im encountering is with this function, when i try to recursively call the function, the cin.get() after "Hit the return key to continue.." doesn't pause and wait for the return key, but if i call the function from outside of itself it works fine. Any words of advice appreciated, thanks.
The following is my test.cpp file, i always write new functions in my test.cpp file until they work, then i put them in my main.cpp file. The function is named helpMenu().
#include <iostream>
#include <stdlib.h>
#ifdef _WIN32
#define CMD_CLEAR "cls"
#endif
#ifdef linux
#define CMD_CLEAR "clear"
#endif
usingnamespace std;
int helpMenu(int choice = 0);
int main() {
helpMenu();
return 0;
}
int helpMenu(int hM_choice) {
if (hM_choice != 0) {
// Argument specified.
if ((hM_choice >= 1) && (hM_choice <= 3)) {
system(CMD_CLEAR);
cout << "\n\n\n\t\t\t";
if (hM_choice == 1) {
cout << "[ How to Play ]\n\n";
cout << "\tThe aim of the game is to build a 5-in-a-row line across\n";
cout << "\tthe grid in any direction before your opponent. This is\n";
cout << "\tthe only way to win the game.\n\n";
} elseif (hM_choice == 2) {
cout << "[ About ]\n\n";
cout << "\tThis game was created for educational purposes by Exussum.\n\n";
cout << "\tE-mail: exussum@gmx.com\n\n";
} else { return 0; }
cout << "\n\n\n Hit the return key to continue..\n";
cin.get();
}
else { helpMenu(); }
}
else {
// No argument, display help menu.
string hM_menuChoice;
system(CMD_CLEAR);
cout << "\n\n\n\t1) How To Play.\n\t2) About.\n\n\t3) Close Help Menu.\n ";
cin >> hM_menuChoice;
if (hM_menuChoice.length() == 1) {
if (hM_menuChoice[0] == '1') { helpMenu(1); }
elseif (hM_menuChoice[0] == '2') { helpMenu(2); }
else { helpMenu(3); }
}
else {
system(CMD_CLEAR);
cout << "\n\n\n\n\n\t\t";
cout << "Invalid menu choice." << ".\n\n\n\n";
sleep(2); helpMenu();
}
helpMenu(2);
}
return 0;
}
First problem is that line 41 calls helpMenu() with no arg. Not even sure how that compiles.
You are trying to do too much in one function.
Break out displaying the menu, getting input, how to play, and about into separate functions, and have one function to tie it all together. That will simplify it greatly.
Lastly, reconsider your use of recursion. This is a poor application of recursion. A while loop would serve you better.
Thanks for your reply, yeah i guess it is a bit too much for one function, i'll break it up. Line 41 calling with no arg, i read earlier on some website about creating functions with default values, so you can call the function with no value (which will resort to using the default value in the function prototype), or by passing a value. Thanks again.