C++ How do I use variables from one function to another? - c++

For the record I am completely green in C++ and any other programming language for that matter, so if it's possible I'd be happy if you can answer in a way that I can understand :)
I have been working on a simple rock, paper, scissors game recently where I have 3 basic functions, one for the user, one for the bot, and one that choose which one wins the game.
I know using system("cls") isn't the best way to go, but I'm not planning on using this outside Windows.
The final function results() need to use the variables x and brand from the two previous functions, however I can't seem to find a way to do this. And where people explain it anywhere else, they explain it too advanced for me. Remeber that I don't need to change any of them, I simply have to compare them to determine the winner.
I'll show you my code here so you can see what you are dealing with.
Please give me comments on other things I can improve here.
#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <windows.h>
using namespace std;
int bgame(), ugame(), results();
int main()
{
srand(time(NULL));
cout<<"Welcome to RPS!\n" <<"You know what to do.\n" <<"\n[ENTER]";
cin.ignore();
system("cls");
ugame();
return 0;
}
int ugame()
{
int x;
cout<<"Type a number from 1-3: ";
cin>> x;
cin.ignore();
if ( x == 1 )
{
cout<<"\nYou chose rock!\n" <<"\n[ENTER]";
cin.ignore();
bgame();
}
else if ( x == 2)
{
cout<<"\nYou chose paper!\n" <<"\n[ENTER]";
cin.ignore();
bgame();
}
else if ( x == 3 )
{
cout<<"\nYou chose scissors!\n" <<"\n[ENTER]";
cin.ignore();
bgame();
}
else
{
cout<<"\nTry again.\n" <<"\n[ENTER]";
cin.ignore();
ugame();
system("cls");
}
return 0;
}
int bgame()
{
int brand = rand()>>4;
system("cls");
cout<<"The bot will now choose an item.\n" <<"\n" <<"[ENTER]\n";
cin.ignore();
brand = rand() % 3 + 1;
if ( brand == 1)
{
cout<<"\nBot chose rock!";
cin.ignore();
results();
}
else if ( brand == 2 )
{
cout<<"\nBot chose paper!";
cin.ignore();
results();
}
else if ( brand == 3 )
{
cout<<"\nBot chose scissors!";
cin.ignore();
results();
}
else
{
cout<<"\nError.";
cin.ignore();
bgame();
system("cls");
}
return 0;
}
int results()
{
}

you can send "parameters" to a function.
That's create a copy of your variable and you can use it in another function.
You need to specifies it with your function name (that's named prototype) like this :
int results(int x, int brand)
You put a type name and a variable name.
For example this function will take 2 int as parameters.
int results(int x, int brand)
{
// do something with your variables
}
And when you call the function you type:
results(x, brand);
If you want, this link explains it with images and examples and more details: http://www.cplusplus.com/doc/tutorial/functions/

First, learn how to use functions with parameters.
After that, you should be able to do what you want.
As suggested, you only have to do something like this :
declaration :
int bgame(int x){
... what bgame do ...
}
and in ugame :
int ugame(){
int x;
...
cin >> x;
...
bgame(x);
}
Hope this helps.

Use parameters, pass by value. Have parameters in the function header, so you can pass the value into the funcion.
using namespace std;
int bgame(int x_p), ugame(), results(int x_p, int brand_p);
int main()
{
srand(time(NULL));
cout<<"Welcome to RPS!\n" <<"You know what to do.\n" <<"\n[ENTER]";
cin.ignore();
system("cls");
ugame();
return 0;
}
int ugame()
{
int x;
cout<<"Type a number from 1-3: ";
cin>> x;
cin.ignore();
if ( x == 1 )
{
cout<<"\nYou chose rock!\n" <<"\n[ENTER]";
cin.ignore();
bgame(x);
}
else if ( x == 2)
{
cout<<"\nYou chose paper!\n" <<"\n[ENTER]";
cin.ignore();
bgame(x);
}
else if ( x == 3 )
{
cout<<"\nYou chose scissors!\n" <<"\n[ENTER]";
cin.ignore();
bgame(x);
}
else
{
cout<<"\nTry again.\n" <<"\n[ENTER]";
cin.ignore();
ugame();
system("cls");
}
return 0;
}
int bgame(int x_p)
{
int brand = rand()>>4;
system("cls");
cout<<"The bot will now choose an item.\n" <<"\n" <<"[ENTER]\n";
cin.ignore();
brand = rand() % 3 + 1;
if ( brand == 1)
{
cout<<"\nBot chose rock!";
cin.ignore();
results(x_p, brand);
}
else if ( brand == 2 )
{
cout<<"\nBot chose paper!";
cin.ignore();
results(x_p, brand);
}
else if ( brand == 3 )
{
cout<<"\nBot chose scissors!";
cin.ignore();
results();
}
else
{
cout<<"\nError.";
cin.ignore();
bgame(x_p);
system("cls");
}
return 0;
}
int results(int x_p, int brand_p)
{
// Do whatever you want to do with x (x_p) and brand (brand_p).
}

For you, you only need to return 1 value for each function, so return would work. Instead of return 0;, use return x; and return brand;. In the comparing function, define two new variables, such as y; or crand;, then assign them like this: y=int ugame(); and crand=int bgame();. Then y=x and crand=brand and you can work from there. So then you don't need any parameters or anything. Also, don't try to define brand straight out, just declare int brand; and let the randomizing function (which must be seeded with srand by the way) assign a value to brand. You also don't have to define the functions as int; they will define themselves.

Related

How to scan for a letter in c++ instead of a number?

My code prompts the user to input 0 or 1 as an integer in answer to one of the questions. I want the user to type Y or N. I tried to create a char variable, but I am not getting it right. It says y and n is not declared. I know it's a basic question, but I have just started learning c++.
Here is my code and below that the prompts, inputs, and output as well as a screenshot.
#include <iostream>
using namespace std;
int main() {
int a; // number of classes held
int b; // number of classed attended
int percent;
cout<<"Number of classes held "<<endl;
cin>>a;
cout<<"Number of classes attended "<<endl;
cin>>b;
percent = (b*100)/a;
if (percent>75 && percent<=100) {
cout<<"Congratulation you are allowed to sit in the examination your attendence is "<<percent<<"%";
} else if (percent<75) {
int m;
cout<<"Do you have any medical cause? (Respond in '1' for yes or '0' for no) "<<endl;
cin>>m;
if (m==1) {
cout<<"You are allwed due to a medical cause your percentage is "<<percent<<"%";
} else if (m==0) {
cout<<"You are not allowed to sit in the examination your percentage is "<<percent<<"%";
} else if (m!=1 && m!=0) {
cout<<"Invalid Responce";
}
} else {
cout<<"invalid attendence";
}
return 0;
}
cout<<"Number of classes held "<<endl;
cin>>a;
cout<<"Number of classes attended "<<endl;
cin>>b;
percent = (b*100)/a;
if (percent>75 && percent<=100) {
cout<<"Congratulation you are allowed to sit in the examination your attendence is "<<percent<<"%";
} else if (percent<75) {
int m;
cout<<"Do you have any medical cause? (Respond in '1' for yes or '0' for no) "<<endl;
cin>>m;
if (m==1) {
cout<<"You are allwed due to a medical cause your percentage is "<<percent<<"%";
} else if (m==0) {
cout<<"You are not allowed to sit in the examination your percentage is "<<percent<<"%";
} else if (m!=1 && m!=0) {
cout<<"Invalid Responce";
}
} else {
cout<<"invalid attendence";
}
return 0;
}
Here is the output of my code:
Number of classes held
100
Number of classes attended
53
Do you have any medical cause? (Respond in '1' for yes or '0' for no)
1
You are allwed due to medical cause your percentage is 53%
screenshot of code and output
Try using char:
char m;
std::cin >> m;
if (m == 'y')
// do something
else if (m == 'n')
// do something else
I think I understood the problem. To do this, you can also include the string library with #include <string>. So you can enter the "y" and "n" values you want as strings.
I leave a sample code for you.
#include <iostream>
#include <string>
using namespace std;
int main() {
string answer;
cout << "yes or no=? ";
cin >> answer;
if(answer == "y")
{
cout << "YES!";
}
else if(answer == "n")
{
cout << "NO!";
}
else {
cout << "TRY AGAIN!";
}
return 0;
}

How could I declare all numbers in one if statement I've try declaring all numbers by else if one by one but it seems the code has logical error

#include <iostream>
using namespace std;
int main ()
{
int quantity;
again:
cout<<"Enter the quantity: ";
cin>>quantity;
If(quantitiy == '1' )
{
total = quantity*price
}
else
{
goto again;
}
return 0;
}
How could I declare all the numbers in one if statement?
Pretty much everything in your code is wrong and needs fixing. Use a do..while loop instead of goto. Correct your typos on If and quantitiy. Declare and initialize the missing total and price variables. Add the missing ; on the total assignment. And '1' and 1 are two completely different types and values.
Try something more like this instead:
#include <iostream>
using namespace std;
int main ()
{
int quantity;
double price = ...; // for you to decide, unless you ask the user...
double total = 0;
do {
cout << "Enter the quantity: ";
cin >> quantity;
}
while (quantity != 1);
total = quantity*price;
return 0;
}
Of course, it really doesn't make sense to prompt the user for a quantity and then only accept 1. You probably want something more like this:
#include <iostream>
using namespace std;
int main ()
{
int quantity;
double price = ...; // for you to decide, unless you ask the user...
double total = 0;
do {
cout << "Enter the quantity (0 to stop): ";
cin >> quantity;
if (quantity == 0) break;
total += (quantity * price);
}
while (true);
return 0;
}

Program compiles but I think switch is ignored.

I am currently studying c++ but I fell behind a little bit, so I apologize if my question is obvious.
I have to create a program that asks for a student's name, GPA, Year of admission, and get a random 5 digit number generated for that person. The number of students will not exceed 42.
My program compiled (somehow) and I am able to get the error for invalid menu selection, however, whenever I give a valid selection (currently 1) nothing happens.
Maybe I am missing something, this is why I need help.
Here is my code.
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
//print all the menu options
void print_menu()
{
cout<<"\nRCNJ Registrar Menu:"<<"\n"
<<"\n"
<<"[1] Add a student"<<"\n"
<<"[2] Display all students"<<"\n"
<<"[3] Display by year"<<"\n"
<<"[4] Display statistics"<<"\n"
<<"[5] Quit"<<"\n";
}
//get and return the student's name
void get_name(string& student_name) //call student_name after that.
{
cout<<"Please enter the sudent's name: ";
cin >> student_name;
cout<<"\n";
}
//validate and return gpa
double get_gpa()
{
double student_gpa = 0;
cout<<"Please enter the GPA: ";
cin >>student_gpa;
cout<<"\n";
while (student_gpa > 4 || student_gpa < 0)
{
cout<<"Please enter a valid GPA for the student (0.00 - 4.00): ";
cin >> student_gpa;
cout<<"\n";
}
return student_gpa;
}
//validateand return year
int get_year()
{
int student_year = 0;
cout<<"Please enter the year: ";
cin >> student_year;
cout<<"\n";
while (student_year >2016 || student_year <1972)
{
cout<<"Please enter a valid year (min 1972, max 2016): ";
cin >> student_year;
cout<<"\n";
}
return student_year;
}
//generate the student's R#
int generate_number()
{
int r_number;
srand (time(NULL));
r_number = rand() % 89999 + 10000;
return r_number;
}
//save info. Include get_name, get_gpa, get_year
void input_new_student()
{
string student_name;
double student_gpa;
int student_year;
int r_number;
int s_name, s_gpa, s_year, r_num;
get_name(student_name);
get_gpa();
get_year();
generate_number();
}
//display all students in the proper format
void print_all()
{
}
//get a year as selection and print all students that are the same year
void print_by_year()
{
}
//display statistics based on entered students
void print_statistics()
{
}
//validate and return the menu option selected by the user.
//it should call print_menu defined earlier
int get_selection(int menu_choice)
{
menu_choice = 0;
cout<<"\n"
<<"Selection: ";
cin >> menu_choice;
cout<<"\n";
while (menu_choice > 5 || menu_choice< 1)
{
cout<<" Menu choice is invalid. Please re-enter (1 - 5): ";
cin>> menu_choice;
cout<<"\n";
}
return menu_choice;
}
int main()
{
string student_name;
double student_gpa;
int student_year;
int r_number;
int menu_choice;
int s_name=0;
int s_gpa=0;
int s_year=0;
int r_num=0;
string nameArray[42];
s_name++;
double gpaArray[42];
s_gpa++;
int yearArray[42];
s_year++;
int ramapoArray[42];
r_num++;
print_menu();
get_selection(menu_choice);
switch (menu_choice)
{
case 1:
input_new_student();
nameArray[s_name] = student_name;
gpaArray[s_gpa] = student_gpa;
yearArray[s_year] = student_year;
ramapoArray[r_num] = r_number;
break;
}
return 0;
}
I dont have permission to comment, hence adding it here.
In you main(),
get_selection(menu_choice);
switch (menu_choice)
You return menu_choice, but there is none to take the value, you end you using garbage value as it is uninitialized.
So two ways you can do it, either by passing the address/reference of menu_choice or by return value. try either of these it should work, though I have not gone through the rest of your program.
As suggested by others, try a debugger e.g. gdb?

Some code to force a user to enter a choice

I'm quite new to c++ and I need help on some code to force a user to make a choice. The first choice calls back the main function and the second choice calls return 0, else the program isn't suppose to return 0 in the main function on any choice. The choice are Y or y for yes and n or N for no, aside these letters the code is not to accept any letter.
I would appreciate it a lot if I receive a help, Thank you.
#include "person. h"
#include <iostream>
#include <string>
using namespace std;
int main()
{
person persons;
persons. getInfo();
persons.showInfo();
cout << "do you want to continue, type Y or y for yes and n or N for no to exit" << endl;
char choice;
cin >> choice;
if (choice == ("Y"||"y"))
{
int main();
}
if (choice == ("N"||"n"))
{
return 0;
}
else
{
cout << "please make a choice"; cin >> choice;
} /* This is where I would like to iterate in other for the user to make one of the choices provided above */
return 0;
}
You could employ something like:
if(choice == "Y" || choice == "y")
int main();
else
return 0;
So they must put Y or y to continue, and then anything else will terminate the program with return 0;

Need 'return to main menu' feature in my C++ code

I have created a C++ program. In this I have added many options for a user.
But in every choice I need to add a function from which a user can either choose to exit the program or can return to the main menu depending upon his choice. So can i have help in my coding.xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
-:
#include<iostream.h>
#include<conio.h>
void main()
clrscr();
int choice,p_card;
char text0,text1;
cout<<"\n\n\t\t\t \"Welcome to Zinc hospital\"\n\n\n";
cout<<"\tMENU\n";
cout<<"\n\n1. Emergency treatment\n\n";
cout<<"2. Common treatment\n\n";
cout<<"3. Regular checkups\n\n";
cout<<"4. Get appointment\n\n";
cout<<"5. Consult specialist\n\n";
cout<<"6. Pay due amount\n\n";
cout<<"7. Log in for new patient card\n\n";
cout<<"8. For suggestions, feedbacks and register complains\n\n";
cout<<"\n\t\t\t\t\t\t\t\tChoice______";
cin>>choice;
clrscr();
if(choice==1)
{
int e_choice;
cout<<"\n\n\n Enter the type of emergency";
cout<<"\n\n1. Accidental case";
cout<<"\n\n2. Heavy injury case";
cout<<"\n\n3. Delicate organ injury\n\n";
cout<<"4. Any other\n\n";
cout<<"\n\n\t\t\t\t\t\t\tEmergency choice____";
cin>>e_choice;
if(e_choice==4)
{
cout<<"Please specify the type of emergency ";
cin>>text0;
}
cout<<"\n\n\n\n\t\t\t \"EMERGENCY DECLARED\"\n\n\t \'Please quickly proceed to the operation theatre with patient\'";
}
if(choice==2)
{
cout<<"\n\nEnter the patient card number\n\n\t";
cout<<"\t\t\tCard No.______";
cin>>p_card;
cout<<"\n\n\t\t\tYour card has been recognized succesfully.";
cout<<"\n\n\nNow enter the specific treatment to be provided___";
cin>>text0;
cout<<"\n\n\n\n \t\t\tDATA recorded succesfully";
cout<<"\n\nYour card has been charged $10.\n\n\n\n Please proceed to counter to get the room no. and wait list serial.";
}
else if(choice==3)
{
cout<<"";//Under construction
}
else if(choice==4)
{
cout<<"";//Under construction
}
else if(choice==5)
{
cout<<"";//Under construction
}
else if(choice==6)
{
cout<<"";//Under construction
}
else if(choice==7)
{
cout<<"";//Under construction
}
else if(choice==8)
{
cout<<"";//Under construction
}
else if(choice!=1&&choice!=2&&choice!=3&&choice!=4&&choice!=5&&choice!=6&&choice!=7&&choice!=8)
{
cout<<"Invalid choice inputed";
cout<<"\n\n\n\n\n\n\t\t#Domain ERROR";
}
getch();
}
Lookup table (one of many solutions).
typedef (void) (P_Function)(void);
struct Menu_Entry
{
unsigned int selection_number;
const char * text;
P_Function p_processing_function;
};
void Process_Emergency_Treatment(void);
void Process_Common_Treatment(void);
Menu_Entry main_menu[] =
{
{1, "Emergency Treatment", Process_Emergency_Treatment},
{2, "Common Treatment", Process_Common_Treatment},
};
static const unsigned int quantity_menu_items =
sizeof(main_menu) / sizeof(main_menu[0]);
// ...
unsigned int selection;
std::cout << "Enter selection: ";
std::cin >> selection;
unsigned int index = 0U;
for (index = 0U; index < quantity_menu_items; ++index)
{
if (main_menu[index].selection_number == selection)
{
main_menu[index].p_processing_function(); // Execute the command processor.
break;
}
}
if (index >= quantity_menu_items)
{
std::cout << "\nInvalid selection, try again.\n";
}
A nice advantage to the lookup table is that when you want to add items to the menu, add an entry into table. Also, you only need to test the search loop once. Adding more entries to the table doesn't effect the execution of the search loop.
Edit 1: Fundamental menu algorithm
The fundamental algorithm can look like this:
bool selection_is_valid = false;
while (!selection_is_valid)
{
Print_Menu();
unsigned int selection = 0U;
std::cout << "Enter selection: ";
std::cin >> selection;
if (select >= MAXIMUM_CHOICES)
{
selection_is_valid = false;
}
else
{
Process_Menu_Item(selection);
selection_is_valid = true;
}
}
With a little skill you can modify the above algorithm to display until an "exist selection" is pressed.