#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.
Related
I am completely new to programming and I am learning C++. I wrote a code to practice Functions with Return Values. The code builds and runs, but there is an error message and I would like some help understanding it.
#include <iostream>
using namespace std;
void showMenu() {
cout << " 1. Change personal information." << endl;
cout << " 2. Search a Record." << endl;
cout << " 3. Delete a Record." << endl;
cout << " " << endl;
}
int getInput() {
cout << "Please select a menu item: " << flush;
int menuNum;
cin >> menuNum;
return menuNum;
}
void processSelection (int options){
int password = 12;
int record = 4;
int record2 = 5;
switch (options) {
case 1:
...
}
int main() {
cout << "" << endl;
showMenu();
int menuSel = getInput();
processSelection (selection);
return 0;
}
I left out all the switch stuff because it takes up so much room.
The error is in int main () at processSelection (selection); It says "Type 'processSelection' could not be resolved."
Thank you
You passed undeclared identifier selection to processSelection function.
Just pass menuSel to processSelection, so your main should look like this:
int main() {
cout << "" << endl;
showMenu();
int menuSel = getInput();
processSelection(menuSel);
return 0;
}
So, my assignment in class was to make a C++ program that essentially makes a database with a number of options (adding to it, deleting entries, modifying, searching and listing). It has to be done specifically with arrays, not vectors or classes or whatever.
I decided to make a number of functions to handle each option, and have them all call each other. After extensive googling, I also decided to let a struct handle the declarations so I can use them in all functions without using :: marks. I specifically made everything depend on each other because the teacher hinted that we're going to have to do further work with it, so if I modify something, everything else changes to accommodate.
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
using namespace std;
struct va{
public:
int i, j, k, l; //for possible loops or variables I only need for a very short time
int id = 0;
int name = id+1;
// like 6 other ints I also declared here, including year2
int achi = year2+1;
//The above is for easier identification of pro[whatever][needed data]. The +1 method is to allow for easier editing later.
int size = 20, row = 0; //This is important for addition
string searchterm = ""; //this is for searching
public:
int main();
void MainMenu();
void Addition();
void Deletion();
void Search();
void Modify();
void List();
};
void MainMenu();
void Addition();
void Deletion();
void Search();
void Modify();
void List();
//I just find it neater to make side functions after the main one.
int main()
{
setlocale(LC_ALL, "");
const int column = achi;
const int initsize = size; //These two are so I can edit the size of the array from the struct directly
string pro[initsize][column]; //This creates the array that's the actual database
cout << endl << "Welcome to the League of Legends Pro Players database!" << endl << endl;
cout << endl << "Please, use the menu to access its functions.";
MainMenu();
cout << endl;
return 0;
}
void MainMenu()
{
cout << endl << "Main Menu" << endl;
cout << endl << "1: add an entry to the database.";
cout << endl << "2: delete an existing entry from the database.";
cout << endl << "3: search for an existing entry in the database.";
cout << endl << "4: modify an existing entry.";
cout << endl << "5: list all existing entries." << endl;
cin >> i;
switch(i)
{
case 1: Addition();
case 2: Deletion();
case 3: Search();
case 4: Modify();
case 5: List();
}
}
(I haven't written the actual functions for options yet.) However, when I tried to run it, I was told 'achi' wasn't declared in main, although I made everything public just so I won't run into this error. How could I make main "see" the struct and its variables?
You have only defined a type, you don't have an values of that type. You have also declared but not defined a number of member functions, and then declared (and presumably defined, tho many are not shown) free functions with the same names.
When providing out-of-class definitions of member functions of struct va, you need to use va:: to qualify the names of the members, to distinguish them from anything else with the same name. If this were not the case, then all the good names would be used up by members of classes in the standard library.
It's also good practice to declare variables at the narrowest possible location. Don't clutter the data members of va with things that can be local to it's member functions.
#include <iostream>
#include <string>
using std::cout;
using std::cin;
using std::endl;
struct va {
static constexpr int size = 20;
static constexpr int column = ???;
std::string pro[size][column];
void MainMenu();
void Addition();
void Deletion();
void Search();
void Modify();
void List();
};
int main()
{
setlocale(LC_ALL, "");
va instance;
cout << endl << "Welcome to the League of Legends Pro Players database!" << endl << endl;
cout << endl << "Please, use the menu to access its functions.";
instance.MainMenu();
cout << endl;
return 0;
}
void va::MainMenu()
{
cout << endl << "Main Menu" << endl;
cout << endl << "1: add an entry to the database.";
cout << endl << "2: delete an existing entry from the database.";
cout << endl << "3: search for an existing entry in the database.";
cout << endl << "4: modify an existing entry.";
cout << endl << "5: list all existing entries." << endl;
int i;
cin >> i;
switch(i)
{
case 1: Addition();
case 2: Deletion();
case 3: Search();
case 4: Modify();
case 5: List();
}
}
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..!! :)
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;
}
Im new to programming and C++ and I started making a little string type game for fun, which gives the user two options through out the program, but in the final part of the program i cant get it to output a unique option for the final input(makeCure) - which i only want to output at the end not through out the program. Hope Im making sense :/ .Iv tried and tried and tried and the more i try the more probloms I create. Iv shown below in my code where Im sure the problom lies. Any advice would much appreciated.
#include<iostream>
#include<string>
using std::string;
bool intro(void);
void room(bool enemy, bool data, bool cure, string description);
//player stats
string Name = "";
//enemy states
string enemyName = "";
//data stats
string dataName = "";
//Cure - Option in room7 only
string makeCure = "";
//room descriptions(string constructs)
const string room1 = "You enter the first town of infected Zombies.";
const string room2 = "You are overwelmed by Zombies, and plunder into the sewers to escape.";
const string room3 = "You make your way to safety and find yourself in the Central Town Hall.";
const string room4 = "You decide to venture into the local forest to find the finalingrediants";
const string room5 = "You venture further for the final ingrediant, into a nearby Cave.";
const string room6 = "Its time for you to face the Zombie General!!!";
const string room7 = "You work day and Night in the Labs to make the Cure.";
int main(void)
{
if(intro())
return 0;
dataName = "First Ingrediant- Zombie Rags with infected DNA";
enemyName = "Zombie Soldior";
room(true, true, false, room1);
enemyName = "Massive Zombie Rat";
room(true, false, false, room2);
dataName = "Seconed Ingrediant- StemCells";
enemyName = "Mutated Scientists";
room(true, true, false, room3);
dataName = "Third Magic-Mushrooms";
room(false, true, false, room4);
dataName = "Fourth Final Ingrediant - Coffee Beans";
enemyName = "Commander Zombie";
room(true, true, false, room5);
enemyName = "Zombie General";
room(false, true, false, room6);
return 0;
makeCure = "Elixier to Save the World";
room(false, false, true, room7);
return 0;
}
bool intro(void)
{
using std::cout;
using std::cin;
cout << "Brave Soul!!! What is your name?\n";
cin >> Name;
cout << "Ahh... " << Name << " You say.." << "How about Zombie Slayer?.. Good, glad we agree!\n";
cout << "Humanity is in need of your Help, "
<< "The world is being infected by the\n"
<< "ZD1678 ZOMBIE VIRUS \n"
<< "And we need to send you to Cape Town to stop the central spread.\n"
<< "Your task will be tough, but we know you can do it \n"
<< "Will you accept the challenge?\n\n";
cout << "1)Yes. \n"
<< "2)No. \n\n";
int response;
cin >> response;
return !(response ==1);
}
void room(bool enemy, bool data, bool cure, string description)
{
using std::cout;
using std:: cin;
while(true)
{
cout << description.c_str() << "\n\n";
int response = 0;
do
{
cout << "Shall Our Hero continue his Quest?\n";
if(enemy)
cout << "1) Attack the "
<< enemyName.c_str() << "\n";
else if(!enemy)
cout << "1) venture further....";
if(data)
cout << "2)Pick up the "
<< dataName.c_str() << "\n";
cin >> response;
/* Trying to create the last if that only kicks in at room7( string makeCure )
* that displays the option to make the cure
* This is where my Problem is.
* Iv tried anouther if
* and else
* and while and nothing works, its just messes up everything..
* badly
*/
} while(response < 1 || response > 2);
switch(response)
{
case 1:
if(enemy)
{
enemy = !enemy;
cout << "You slay the deadly "
<< enemyName.c_str() << "\n";
}
else if(!enemy)
return;
break;
case 2:
data = !data;
cout << "You pick up the "
<< dataName.c_str() << "\n";
break;
}
}
}
what you probably want to do is dynamically generate a list of possible events each time you write out the list and present it to the user, then you can match the response to the list to get what the user wants to do. like this:
enum EventType
{
ET_Enemy,
ET_Item,
ET_Cure,
ET_Continue,
ET_MAX
};
void room(bool enemy, bool data, bool cure, string description)
{
using std::cout;
using std:: cin;
int currentEventChoices[ET_MAX];
int numEventChoices;
while(true)
{
cout << description.c_str() << "\n\n";
int response = 0;
do
{
numEventChoices = 0;
cout << "Shall Our Hero continue his Quest?\n";
if(enemy)
{
cout << (numEventChoices+1) << ") Attack the "
<< enemyName.c_str() << "\n";
currentEventChoices[numEventChoices] = ET_Enemy;
numEventChoices++;
}
if(data)
{
cout << (numEventChoices+1) << ") Pick up the "
<< dataName.c_str() << "\n";
currentEventChoices[numEventChoices] = ET_Item;
numEventChoices++;
}
if(cure)
{
cout << (numEventChoices+1) << ") cure related string "
<< makeCure.c_str() << "\n";
currentEventChoices[numEventChoices] = ET_Cure;
numEventChoices++;
}
cout << (numEventChoices+1) << ") venture further....\n"; // note if this is only meant to be an option if there is no enemy, put it in an else after the if(enemy)
numEventChoices++;
cin >> response;
} while(response < 1 || response > numEventChoices);
switch(currentEventChoices[response-1])
{
case ET_Enemy:
enemy = !enemy;
cout << "You slay the deadly "
<< enemyName.c_str() << "\n";
break;
case ET_Item:
data = !data;
cout << "You pick up the "
<< dataName.c_str() << "\n";
break;
case ET_Cure:
//do cure stuff
break;
case ET_Continue:
return;
}
}
}
the trouble you are having is that by just using a very static next of if/else statements each time you want to match the option number to the event, it gets very complex and messy, it was fine when there was just the 4 cases of there being an enemy or not, or data or not. but now you are adding another branch with cure, its just got really complex to do it that way.
It's a bit hard to understand what you need, so tell me if it's not what you wanted.
Using braces and indenting consistently can really help with this:
do {
cout << "Shall Our Hero continue his Quest?\n";
if (enemy) {
cout << "1) Attack the " << enemyName << "\n";
} else {
cout << "1) venture further....";
}
if (data) {
cout << "2) Pick up the " << dataName << "\n";
}
if (cure) {
cout << "2) take the " << makeCure << "\n";
}
cin >> response;
} while (response < 1 || response > 2);
and fix "case 2" in the switch part:
case 2:
if (data) {
data = false;
cout << "You pick up the " << dataName << "\n";
} else if (cure) {
// fill in ...
}
break;
Notes:
You can use endl (from std) instead of '\n'. cout << "hello" << endl;
You can pass many of your global variables as arguments, so you won't need them to be global (global is bad, in general).
Much of your game can be be squeeszed into arrays and structs - being "data driven" and "table driven". I don't know if you got there already, but you can try and identify these parts.
if(enemy) ... else if(!enemy) you don't need the !enemy part. it is implied by the else.