Switch in "main.cpp" is skipping cases with function from "stack.cpp" - c++

I have 3 files: one with stack define by class in stack.h, second with stack's functions in stack.cpp, and last one is main.cpp. In main(), I have a switch for an interactive menu:
#include <iostream>
#include "Stack.h"
int main() {
stack s; //for calling functions from stack.cpp
char choise;
menu:
system("cls");
std::cout << "a => create stack\n" << "b => read data to stack\n" << "c => show data in stack\n" << std::endl; //so it looks like that somehow
switch(choise) {
case 'a':
s.stack(); // function in stack.cpp
std::cout << "Stack was created" << std::endl;
goto menu;
case 'b':
s.getdata(); //function in stack.cpp
goto menu;
case 'c':
s.display();
goto menu;
}
// and another...
The problem is when I'm calling, for example, 'b', the program is like skipping it and doesn't call the function from stack.cpp. So I can't write or make any other case.

Maybe you are missing "break;" in end of each case block?
Try with
do
{
system("cls");
std::cout << "a => create stack\n" << "b => read data to
stack\n" << "c => show data in stack\n" << std::endl; //so it
lookss like that somehow
std::cin >> choise //As Adrian said
switch(choise) {
case 'a':
s.stack(); // function in stack.cpp
std::cout << "Stack was created" << std::endl;
break;
case 'b':
s.getdata(); //function in stack.cpp
break;
case 'c':
s.display();
break;
}
// and another...
}while(1);

Related

Query about a given function's use in the code

i'm following this tutorial and they give us this code to test the function isLowerVowel:
#include <iostream>
bool isLowerVowel(char c, bool yIsVowel)
{
switch (c)
{
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
return true;
case 'y':
return (yIsVowel ? true : false);
default:
return false;
}
}
int main()
{
std::cout << std::boolalpha;
std::cout << isLowerVowel('a',false) << "\n";
std::cout << isLowerVowel('a',true) << "\n";
std::cout << isLowerVowel('q',false) << "\n";
std::cout << isLowerVowel('q',true) << "\n";
std::cout << isLowerVowel('y',false) << "\n";
std::cout << isLowerVowel('y',true) << "\n";
return 0;
}
I dont understand what the use of yIsVowel is for, shouldnt just testing isLowerVowel be enough? Sorry i asked them but got no replies
I dont understand what the use of yIsVowel is for, shouldnt just testing isLowerVowel be enough?
If you were to use the isLowerVowel fuction to implement the isLowerVowel function you would have recursion. It is unclear how this recursion should be terminated.
yIsVowel appears to be used to set whether y is a vowel or not.

c++ switch statement: group cases and give particular instruction for each case

Consider the following code:
int main()
{
const int a = 9;
switch (a)
{
case 9:
// since a is 9, this ("good") should be printed
std::cout << " good " << std::endl;
case 4:
// since a is not 4, this ("bad") should not be printed
std::cout << " bad " << std::endl;
// for both a==9 or a==4, this should be printed
{
std::cout << " always print me " << std::endl;
break;
}
}
}
The result should then be:
good
always print me
However this is not working. It there a way to do that in C++? Thanks!
There is no way of doing what you ask for inside a switch-statement short of using goto:
#include <iostream>
int main()
{
const int a{ 9 };
switch (a)
{
case 9:
std::cout << "good\n";
goto foo;
case 4:
std::cout << "bad\n";
goto foo;
foo:
std::cout << "always print me\n";
break;
}
}

C++ Being able to exit from a function at any given time

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..!! :)

C++ Function Parameters: Passing Data to Subroutines and variables

#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.

How to Access a Dynamic struct from an external function C++?

I'm trying to make a very simple text-based game and I encountered an error when I tried to access a dynamic struct from an external function. I initialized all variables and structs in my header file and declared a dynamic alloc in the main function. But still I got errors. Am I missing something? This is my code.
==================main function "new.cpp"====================
#include <stdlib.h>
#include <iostream>
#include <string>
#include "game.h"
using namespace std;
difficulty _df_1;
player* player_1 = new player[3];
int main()
{
//initialize player stats
player_1->hp = 100;
player_1->life = 3;
player_1->mana = 50;
player_1->player_id = 1;
player_1->level = 1;
player_1->player_name= "emmet";
//..end
int turn=1;
cout << "What is your name? <<<";
getline(cin,player_1->player_name,'\n');
cout << "Choose a difficulty level: [0]Easy [1]Normal [2]Godlike" << endl;
int ch;
cin >> ch;
switch(ch)
{
case 0:
cout << "Scardy Cat chose EASY." << endl;
break;
case 1:
cout << "A really nice way to start. NORMAL" << endl;
break;
case 2:
cout << "Overly Manly Man is playing GODLIKE." << endl;
break;
default: cout << "I wonder how you can play this game if you can even read simple instructions."<< endl;return 0; break;
}
while(turn == 1)
{
char ch;
cout << "What do you want to do now? \n <<<<";
cin >> ch;
cin.ignore(5,'\n');
switch(ch)
{
case 'a': case 'A':
player_stat();
break;
case 'v': case 'V':
cheat_menu();
break;
case 'x': case 'X':
return 0;
break;
case '`':
break;
default: cout << "We were unable to process your request. Please try again" << endl; break;
}
}
delete player_1;
return 0;
}
void cheat_menu()
{
cout << "CHEATERS WILL ROT IN THE DEEPEST DEPTHS OF TARTARUS." << endl;
cout << "Enter Code:" << endl;
string cheat;
getline(cin,cheat,'\n');
if(cheat == "poo")
{
system("sleep 3");
cout << "Cheat Activated.." << endl;
player_1->hp += 1000;
player_1->level += 10;
player_1->mana += 1000;
player_stat();
}
else
{
cout << "Wrong cheat code.." << endl;
}
//system("sleep 3");
//system("clear");
}
==================end main function==============
=======external func "player_stat.cpp"===========
#include <iostream>
#include "game.h"
using namespace std;
void player_stat()
{
cout << "Name: " << player_1->player_name << endl
<< "Hp: " << player_1->hp << endl
<< "Life: " << player_1->life << "\t Mana: " << player_1->mana << endl
<< "Level: " << player_1->level << "\t XP: " << player_1->xp
<< endl;
//system("sleep 3");
//system("clear");
}
==================end external func==============
==========header file "game.h"===================
#ifndef _GAME_
#define _GAME_
#include "player_stat.cpp"
using namespace std;
//function prototypes...
void player_stat();
void cheat_menu();
//structs for player and NPC
struct player
{
string player_name;
int life;
double atk;
double hp;
double mana;
int player_id;
int level;
long int xp;
string weapon_name;
double weapon_damage;
};
enum difficulty {EASY,NORMAL,GODLIKE};
#endif
===========end header file=======================
These are the errors I got. Please don't mind the other left out functions in int main(). :P
In file included from game.h:4
from new.cpp
in function `void player_stat()':
`player_1' undeclared (first use in this function)
(Each undeclared identifier is reported only once for each function it appears in.)
At global scope:
`player*player_1' used prior to declaration
You declare the variable using the extern storage specifier:
extern player* player_1;
This tells the compiler that the player_1 variable is defined somewhere else, and the linker will resolve it later.
Also as I noted you actually allocate three player objects. If you only need one then don't allocate three:
player* player_1 = new player;
However, that's not needed either, declaring a normal non-pointer variable will work just as fine:
player player_1;
Then in the other files you use extern to tell the compiler that the variable is defined somewhere else:
extern player player_1;
add
extern player* player_1;
to game.h
this will make the player_1 variable available across all the modules.
also remove
#include "player_stat.cpp"
you are not supposed to include any cpp files in the header files