This example is a very basic and simple program.
I want to be able to exit from a function whenever the user wants to.
In the add() function i'm able to exit on the
cin>>NumA;
line by typing 9999 and it will return me to the menu. However i would only be able to exit at this point, so if i wanted to exit at any time i'd have to add the
if (NumA == 9999)
{
return;
}
throught all of the program. I want to be able to exit at any time inside of the function, even better if it can be done by pressing a key, like backspace.
I suppose there is a better way to implement this, how can i do this? Maybe another function :^)
void add()
{
cout << "Addition" << endl;
cout << "Number A: ";
int NumA;
cin>>NumA;
if (NumA == 9999)
{
return;
}
cout << "Number B: ";
int NumB;
cin>>NumB;
int Result = NumA + NumB;
cout << NumA << " + " << NumB << " = " << Result<<endl;
}
int main()
{
int Op;
do
{
cout << "Main" << endl;
cout << "1) Add" << endl;
cout << "2) Another function call" << endl;
cout << "3) Yet another function call" << endl;
cout << "n) ..." << endl;
cout << "0, to exit" << endl;
cin>>Op;
switch (Op)
{
case 1:
{
add();
}
default:
{
break;
}
}
}
while (Op != 0);
}
Most easiest option would be to handle exit point in one of the
Switch case statement as follows.
*** Also don't forget to add break statement after every case statement
switch (Op)
{
case 1:
add();
break ;
case 0:
return 0 ;
break ;
default:
cout << "Invalid option" << endl;
break;
}
Thanks
Well, I tried to write a small sample program as per your description. I am not sure if it will work on Visual Studio. I compiled it on MacOS using g++. The below code may not be a good way of writing a program, but it sort of works, and maybe helpful for your cause.
I modified your code to make a simpler program for better understanding -
#include <signal.h>
#include <stdlib.h>
#include <iostream>
int sum = 0;
int main(); // Prototyping main() is also not recommended
void siginthandler(int param)
{
std::cout << "[INTERRUPT] Sum so far => " << sum << "\n";
main(); // main() shouldn't be called here, but rather some menu function
}
void add()
{
std::cout << "Addition\n";
std::cout << "Enter a number : ";
int NumA;
std::cin >> NumA;
sum += NumA;
std::cout << "[ADD] Sum so far => " << sum << "\n";
}
int main()
{
// Register the SIGINT handler with the main()
signal(SIGINT, siginthandler);
int Op;
do
{
std::cout << "Main" << std::endl;
std::cout << "1) Add" << std::endl;
std::cout << "2) Another function call" << std::endl;
std::cout << "0, to exit" << std::endl;
std::cin>>Op;
switch (Op)
{
case 1:
{
add(); break;
}
default:
{
break;
}
}
}
while (Op != 0);
std::cout << "[MAIN] Sum so far => " << sum << "\n";
exit(0);
}
It does compile on g++, so I am not sure if it will work for your case or not.
Below is the output I got by executing the program :
Abhinavs-MacBook-Pro:test abhinav$ ./a.out
Main
1) Add
2) Another function call
0, to exit
1
Addition
Enter a number : 34
[ADD] Sum so far => 34
Main
1) Add
2) Another function call
0, to exit
1
Addition
Enter a number : 56
[ADD] Sum so far => 90
Main
1) Add
2) Another function call
0, to exit
^C[INTERRUPT] Sum so far => 90
Main
1) Add
2) Another function call
0, to exit
0
[MAIN] Sum so far => 90
Abhinavs-MacBook-Pro:test abhinav$
I hope the above code helps. May the force be with you..!! :)
Related
I'm trying to create multiple calculators in the C++ console for Geometry Theorems and other formulas in Algebra, and for some weird reason on the start of the program, when selecting an option the variable scene does not want to change(shown before the array of calculators[], and instead of going to the Pythagorean Theorem(scene 1), the console says, "Press any key to continue. . ." and closes.
I've tried both the switch() andif() statements to navigate scene management, but what am I doing incorrectly? (I'm still a C++ learner by the way, but I have other programming language experience).
Thanks for the help in advance.
#include "stdafx.h"
#include <iostream>
#include <cmath>
int scene(0);
char calculators[3][25] =
{
"",
"Pythagorean Theorem",
"Homer's Formula"
};
void selection()
{
std::cout << "Enter a number to select a calculator." << std::endl; // Opening
for (int i = 1; i <= 2; i += 1) {
std::cout << "Option " << i << ": " << calculators[i] << std::endl;
}
}
void pTheorem()
{
int a;
int b;
std::cout << "Enter side a: ";
std::cin >> a;
std::cout << "Enter side b: ";
std::cin >> b;
std::cout << "Side length of c is " << sqrt(pow(a, 2) + pow(b, 2)) << std::endl;
}
int main()
{
switch(scene)
{
case 0:
selection();
std::cin >> scene;
std::cout << "You've selected the " << calculators[scene] << " Calculator" << std::endl;
break;
case 1:
pTheorem();
break;
}
return 0;
}
Your main problem is that scene has been declared and initialized 0 at the beginning(globally) itself. This will give you always the same switch case = 0. Changing scene inside the switch cases will not work. Instead, you need to input the scene before the switch.
int main()
{
selection();
int scene = 0;
std::cin >> scene;
switch(scene)
{
......
}
}
Secondly, use std::string instead of char array and use std::vector<>/std::array to store them. For example:
std::array<std::string,2> calculators =
{
"Pythagorean Theorem",
"Homer's Formula"
};
and for loop can be:
for (int i = 0; i < 2; ++i)
std::cout << "Option " << i+1 << ": " << calculators[i] << std::endl;
Problem description
I am trying to solve the following problem:
Implement an algorithm to print all valid (e.g., properly opened and
closed) combinations of n-pairs of parentheses. EXAMPLE: input: 3
(e.g., 3 pairs of parentheses) output: ()()(), ()(()), (())(), ((()))
The moment I rearch the base case and when the calls are being popped from from stack, it is always jumping to following part of the code;
cout <<"==============> RESTART HERE " << endl;
Question
Why isn't the cursor returning to the beginning of the function after the return statement. Why is it restarting from cout <<"==============> RESTART HERE " << endl;
In this code for instance it always restarts from the beginning:
void HelloWorld(int count)
{
if(count<1) return;
if(count<0) return;
cout << " Hello World!" << endl;
HelloWorld(count - 1);
}
The following picture shows the call stack for the first run.
Source code
# include<stdio.h>
#include <iostream>
using namespace std;
# define MAX_SIZE 100
void _printParenthesis(int pos, int n, int open, int close);
/* Wrapper over _printParenthesis()*/
void printParenthesis(int n)
{
if(n > 0)
_printParenthesis(0, n, 0, 0);
return;
}
void _printParenthesis(int pos, int n, int open, int close)
{
static char str[MAX_SIZE];
if(close == n)
{
cout <<" open " << open <<" close " << close <<" " << pos<< endl;
cout << str << endl;
return;
}
else
{
if(close < open) {
str[pos] = '}';
cout <<" B open " << open <<" close " << close <<" " << pos<< " }" << endl;
_printParenthesis(pos+1, n, open, close+1);
}
cout <<"==============> RESTART HERE " << endl;
if(open < n) {
str[pos] = '{';
cout <<" A open " << open <<" close " << close <<" " <<pos << " {" << endl;
_printParenthesis(pos+1, n, open+1, close);
}
}
}
/* driver program to test above functions */
int main()
{
int n = 3;
printParenthesis(n);
getchar();
return 0;
}
You are probably running a debugger on optimized code. There's nothing wrong with doing that, but the optimizer may have reordered code. If the out-of-order execution bothers you, turn off the optimizer when you use the debugger.
#include <iostream>
using namespace std;
void show_menu ()
{
cout << "Welcome" << endl;
cout << "1) Match line-up" << endl;
cout << "2) Match result" << endl;
cout << "3) Quit program" << endl;
}
int selection ()
{
cout << "Select option" << endl;
int input;
cin >> input;
return input;
}
int process (int x)
{
switch(x)
{
case 1:
cout << "Line ups" << endl;
case 2:
cout << "Arsenal 3 - Crystal Palace 0" << endl;
case 3:
cout << "Quitting" << endl;
default:
cout << "Select Option1" << endl;
}
}
int main ()
{
show_menu();
int input2 = selection ();
process(input2);
return 0;
}
So this is a code for some menu and input option, i wrote it as a exercise on subroutins, but in the function below i had a problem that i solved throgh some trile and arror, but still i dont get it.
int process (int x)
{
switch(x)
{
case 1:
cout << "Line ups" << endl;
case 2:
cout << "Arsenal 3 - Crystal Palace 0" << endl;
case 3:
cout << "Quitting" << endl;
default:
cout << "Select Option1" << endl;
}
}
Why do i need the variable (int x) in order dor this function to work?
i have a feel that i dont understand something very basic. pls help)
OK , so the function name is process (meaning you need to process something)
NOW , in order for your function to process something you need to give it that thing to be processed , right?
and the x variable which is an int data type ( int data type because it reflect the same value that was assigned inside your main method "input") is your argument that will be matched with the proper switch case as specified inside your process function.
one more thing , since you are not returning anything through your function , you don't need to declare it as an int , you only need to declare a data type for a function when you return the same data type , so in this case your function could be void.
hope this will help :)
The switch part checks whether the value of int x is 1,2,3 or default(something other than 1,2 and 3) and take the appropriate action(the different cout for each case).
There is no way for it to check the value of int x if you don't pass int x to the process function. I hope this makes things clear.
So heres what im trying to do with my text based rpg now. I want to clean up my main.cpp so that it isnt so long and cluttered, so I am creating a few different cpp files that will hold related items.
I have a maketoon.cpp file that will go through some switch statements that will set all the modifiers(str, int, agl, maxhp) based on the class they choose(class being like lumberjack doctor etc not classes in the object sense of things).
when setting the variables in the maketoon.cpp(within a function called makeMainPlayer() ) i use setters that i made within my createcharacter.h file.
So before you look at my code below, i have a few questions.
1)Where should i create the object(main.cpp, maketoon.cpp). Currently i was creating the object Player in the maketoon.cpp file but im getting these errors:
||=== Build: Debug in 6_days_to_escape (compiler: GNU GCC Compiler) ===|
C:\...\maketoon.cpp||In function 'int makeMainPlayer()':|
C:\...\maketoon.cpp|5|error: 'startChoices' was not declared in this scope|
C:\...\maketoon.cpp|6|error: 'name' was not declared in this scope|
C:\...\main.cpp||In function 'int main()':|
C:\...\main.cpp|39|error: 'Player' was not declared in this scope|
||=== Build failed: 3 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|
2)Should i capitalize the first letting in my object name?
3)how do i call makeMainPlayer in my main.cpp so set that specific objects values to then start the game?
4)Lastly, when i was testing to see if the setters and getters were working, i was getting another Player not declared in this scope error, so i tried just banging out another CreateCharacter Player;at the start of my int main, but i feel that will overwrite all the values set in the later functions, with the default null values.
Also. I know nothing about pointers, but if that is the best way to go(some google searches popped up with this as a fix to similar scenarios)
Seriosly thanks a ton! Im trying to teach myself OOc++ and it is proving difficult. Getting lost in the online tuts and youtube tuts.
//main.cpp
//game rpg
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <conio.h>
#include "createcharacter.h"
#include "maketoon.cpp"
using namespace std;
//is running check
bool running = 1;
//int healedHP(int x, int y);
//int attackedHP(int x, int y);
//user input var+
int userInput = 0;
int startChoices[4] = {0, 0, 0, 0};
string name;
//function declarations
void theStart();
void newGame();
int main (){
void makeMainPlayer();
cout << "Enter your name." << endl;
cin >> name;
cout << "Welcome " << name << "." << endl;
cout << "Strike any key....if you dare......";
getch();
system("cls");
theStart();
makeMainPlayer();
cout << "Name: " << Player.getplayerName() << endl;
cout << "Health: " << Player.getplayerHealth() << endl;
cout << "Strength: " << Player.getStr() << endl;
cout << "Int: " << Player.getInt() << endl;
cout << "Agility: " << Player.getAgl() << endl;
cout << "Difficulty: " << Player.getDifficulty() << endl;
system("pause");
return EXIT_SUCCESS;
}
void theStart()
{
cout << "\n\n";
cout << "\t6 Days to Escape!\n"; //title
cout << "\t\t 1: Play\n"; //main menu options. The first thing the user sees.
cout << "\t\t\t 2: Exit\n";
cin >> userInput;
system("cls");
if(userInput == 1)
{
// Create a new game
newGame();
}
else
{
//bool then false causeing program to exit
running = 0;
}
return;
}
void newGame(){
// there are 4 addresses in this array for the following:
//0. Difficulty
//1. Class
//2. Starting Wep
//3. Boost not implimented yet TODO
//enum class difficulty{simple, easy, hard, impossible};
do{
cout << "Choose Your difficulty: " << endl;
cout << "\t1. Simple - Game practically plays itself." << endl;
cout << "\t2. Easy - Not that easy." << endl;
cout << "\t3. Hard - Zombies do more than crave flesh." << endl;
cout << "\t4. Impossible - You will not make it." << endl;
cin >> startChoices[0];
cout << endl;
system("cls");
if(startChoices[0] < 1 || startChoices[0] > 4){
cout << "Invalid Difficulty Choice. Try again." << endl;}
}while(startChoices[0] < 1 || startChoices[0] > 4);
do{
cout << "Choose your class:" << endl;
cout << "\t1. Lumber Jack - Stong, hard to kill, but slow." << endl;
cout << "\t2. Doctor - Healer, weak but fast. Favors health." << endl;
cout << "\t3. Theif - FAST, Cunning but weak attacks." << endl;
cout << "\t4. Everydayer - Balenced everything." << endl;
cin >> startChoices[1];
cout << endl;
system("cls");
if(startChoices[1] < 1 || startChoices[1] > 4){
cout << "Invalid Class Choice. Try again." << endl;}
}while(startChoices[1] < 1 || startChoices[1] > 4);
do{
cout << "Choose your starting Weapon:" << endl;
cout << "\t1. Axe" << endl;
cout << "\t2. Crowbar" << endl;
cout << "\t3. Swiss army knife" << endl;
cout << "\t4. Ice pick" << endl;
cin >> startChoices[2];
cout << endl;
if(startChoices[0] < 1 || startChoices[0] > 4){
cout << "Invalid Weapon Choice. Try again." << endl;}
}while(startChoices[2] < 1 || startChoices[2] > 4);
}
//----------------------------------------------------------------------------------------
//createcharacter.h
#ifndef CREATECHARACTER_H
#define CREATECHARACTER_H
class CreateCharacter{
public:
//setter
void setplayerName(std::string x){
playerName = x;}
void setwepSpeed(int v){
wepSpeed = v;}
void setplayerHealth(int h){
playerHealth = h;}
void setplayerMaxHealth(int mh){
playerMaxHealth = mh;}
void setplayerStr(int s){
playerStr = s;}
void setplayerAgl(int a){
playerAgl = a;}
void setplayerInt(int i){
playerInt = i;}
void setplayerDifficulty(int d){
playerDifficulty = d;}
void setwepbaseDmg(int j){
wepbaseDmg = j;}
//getters
std::string getplayerName(){
return playerName;}
int getplayerHealth(){
return playerHealth;}
int getMaxHealth(){
return playerMaxHealth;}
int getStr(){
return playerStr;}
int getAgl(){
return playerAgl;}
int getInt(){
return playerInt;}
int getDifficulty(){
return playerDifficulty;}
private:
std::string playerName;
int playerHealth;
int playerMaxHealth; //absolute max = 200
int playerStr; // absolute max = 20
int playerAgl;// absolute max = 20
int playerInt;// absolute max = 20
int playerDifficulty; // absolute max = 4
//items
int wepbaseDmg;
int wepSpeed;
};
#endif
//------------------------------------------------------------------------------
//maketoon.cpp
//This was my attempt based off google....
//int* startChoices[4]={getDifficulty(), get};
int makeMainPlayer(){
CreateCharacter Player;
Player.setplayerDifficulty(startChoices[0]);
Player.setplayerName(name);
switch(startChoices[1]){
case 1:
Player.setplayerMaxHealth(175);
Player.setplayerStr(18);
Player.setplayerAgl(10);
Player.setplayerInt(6);
break;
case 2:
Player.setplayerMaxHealth(200);
Player.setplayerStr(9);
Player.setplayerAgl(13);
Player.setplayerInt(15);
break;
case 3:
Player.setplayerMaxHealth(100);
Player.setplayerStr(11);
Player.setplayerAgl(20);
Player.setplayerInt(10);
break;
case 4:
Player.setplayerMaxHealth(150);
Player.setplayerStr(12);
Player.setplayerAgl(12);
Player.setplayerInt(13);
break;
}
switch(startChoices[2]){
case 1:
Player.setwepbaseDmg(40);
Player.setwepSpeed(4);
break;
case 2:
Player.setwepbaseDmg(30);
Player.setwepSpeed(5);
break;
case 3:
Player.setwepbaseDmg(25);
Player.setwepSpeed(8);
break;
case 4:
Player.setwepbaseDmg(20);
Player.setwepSpeed(10);
break;
}
return 0;
}
I'm following a tutorial for making a MUD (text-based RPG), and I am having issues with my main function. If you'll look at the code, you'll see that when the player moves it will check for a random encounter, and if monster != 0, it will go into the combat loop. When I execute this in the command prompt, it will allow me to attack the monster, but it never makes it to the monster->attack(mainPlayer) function. It just goes back to the screen that states whether I want to move, rest, view stats, or quit. Any help with this would be greatly appreciated!
#include "stdafx.h"
#include "Map.h"
#include "Player.h"
#include <cstdlib>
#include <ctime>
#include <iostream>
using namespace std;
int main()
{
srand( time(0) );
Map gameMap;
Player mainPlayer;
mainPlayer.createClass();
// Begin adventure
bool done = false;
while( !done )
{
// Each loop cycle we output the player position and
// a selection menu.
gameMap.printPlayerPos();
int selection = 1;
cout << "1) Move 2) Rest 3) View Stats 4) Quit: ";
cin >> selection;
Monster* monster = 0;
switch( selection )
{
case 1:
// Move the player
gameMap.movePlayer();
// Check for a random encounter. This function
// returns a null pointer if no monsters are
// encountered.
monster = gameMap.checkRandomEncounter();
// 'monster' not null, run combat simulation.
if( monster != 0)
{
// Loop until 'break' statement.
while( true )
{
// Display hitpoints
mainPlayer.displayHitPoints();
monster->displayHitPoints();
cout << endl;
// Player's turn to attack first.
bool runAway = mainPlayer.attack(*monster);
if( runAway )
{
break;
}
if( monster->isDead() )
{
mainPlayer.victory(monster->getXPReward());
mainPlayer.levelUp();
break;
}
monster->attack(mainPlayer);
if( mainPlayer.isDead() )
{
mainPlayer.gameover();
done = true;
break;
}
}
// The pointer to a monster returned from
// checkRandomEncounter was allocated with
// 'new', so we must delete it to avoid
// memeory leaks.
delete monster;
monster = 0;
}
break;
case 2:
mainPlayer.rest();
break;
case 3:
mainPlayer.viewStats();
break;
case 4:
done = true;
break;
} // End switch statement
} // End While statement
} // End main function
Here is the Player::attack function:
bool Player::attack(Monster& monster)
{
int selection = 1;
std::cout << "1) Attack 2) Run: ";
std::cin >> selection;
std::cout << std::endl;
switch( selection )
{
case 1:
std::cout << "You attack the " << monster.getName()
<< " with a " << mWeapon.mName << std::endl;
if( Random(0, 20) < mAccuracy )
{
int damage = Random(mWeapon.mDamageRange);
int totalDamage = damage - monster.getArmor();
if( totalDamage <= 0)
{
std::cout << "Your attack failed to penetrate the "
<< monster.getName() << "'s armor." << std::endl;
}
else
{
std::cout << "You attack for " << totalDamage
<< " damage!" << std::endl;
// Subtract from monster's hitpoints.
monster.takeDamage(totalDamage);
}
}
else
{
std::cout << "You miss!" << std::endl;
}
std::cout << std::endl;
break;
case 2:
// 25% chance of being able to run.
int roll = Random(1, 4);
if( roll == 1 )
{
std::cout << "You run away!" << std::endl;
return true; //<-- Return out of the function.
}
else
{
std::cout << "You could not escape!" << std::endl;
break;
}
}
}
And here is the Monster::attack function:
void Monster::attack(Player& player)
{
cout << "A " <<mName << " attacks you "
<< "with a " << mWeapon.mName << std::endl;
if( Random(0,20) < mAccuracy )
{
int damage = Random(mWeapon.mDamageRange);
int totalDamage = damage - player.getArmor();
if( totalDamage <= 0 )
{
cout << "The " << mName << "'s attack failed to "
<< "penetrate your armor." << endl;
}
else
{
cout << "You are hit for " << totalDamage
<< " damage!" << endl;
player.takeDamage(totalDamage);
}
}
else
{
cout << "The " << mName << " missed!" << endl;
}
cout << endl;
}
Your Player::attack() method has only one return-statement: return true;. You forgot to add the final line return false; to your method.
This could have easily been prevented if you enable warnings (and pay attention to them!)
Your Player::attack doesn't return in all cases (specifically when it needs to return false). When the calling function tries to access the return value of Player::Attack it will get junk and so you enter the if(ranAway) block and break out of your while loop