how to make my program run again C++ - c++

I have given the following question.
Write a menu driven program with following options:
Add new value
Search value
Modify value
Print value
Print sum of all values
Quit / Terminate
You have to create 5 options as five function. Add another function to show menu options.
and here is my code:
#include<iostream>
using namespace std;
float f[100]={0};
//1st option
void AddNewValue(){int input;
cout<<"Enter a value\n";
cin>>f[input];
}
//2nd option
void SearchValue(){int i, search;
cout<<"Enter a value to search\n";
cin>>search;
int match=0;
for (int i=1;i<=100;i++)
{if (f[i]==search)
{match=1;
break;}
}
if (match==1){cout<<"Matched value found\n";
}
else {cout<<"No match found\n";}
}
//3rd option
void ModifyValue(){int input1;
cout<<"Enter the position at which you want to modify value\n";
cin>>input1;
cout<<"Enter a value\n";
cin>>f[input1-1];
}
//4th option
void PrintValue(){int i;
for (i=1;i<=100;i++)
{cout<<f[i]<<' ';}
}
//5th option
void PrintSum(){int i,sum;
for(i=1;i<=100;i++)
{sum=f[i]+f[i+1];}
cout<<"Sum is : "<<sum;
}
//starting Function
void menu(){int x;
cout<<"Enter an option: \n";
cout<<"1- Add new value\n2- Search Value\n3- Modify value\n4- Print Value\n5- Print sum of all values\n6- Quit/terminate\n";
cin>>x;
if(x==1){
AddNewValue();
}
else if (x==2){
SearchValue();
}
else if(x==3){
ModifyValue();
}
else if(x==4){
PrintValue();
}
else if(x==5){
PrintSum();
}
else{
}
}
int main(){
menu();
}
And I want to make my full program run again and again until the user enter a wrong option.

One option available to you is to create a while loop encapsulating the body of your menu() function, and using break; if the user enters 6.
void menu(){
int x = 0;
while(1){
cin >> x;
//your code here
if(x==6)
break;
}
}
This example will cause your menu to repeat until the user enters 6.
The purpose of break; is to 'break' from the while loop. In this case, breaking will end your menu()and return to main().
Further, it is good practice to add return 0; to the end of your main function.

You can use a loop and make it run untill user give a specific input. In below code once the program will run and then it will ask user to input 5 to exit or any other key to run again, and if user gives 5 as input, then it will stop or if user gives any other input then program will run again.
Hope it is clear and help you.
#include<iostream>
using namespace std;
float f[100]={0};
//1st option
void AddNewValue(){int input;
cout<<"Enter a value\n";
cin>>f[input];
}
//2nd option
void SearchValue(){int i, search;
cout<<"Enter a value to search\n";
cin>>search;
int match=0;
for (int i=1;i<=100;i++)
{if (f[i]==search)
{match=1;
break;}
}
if (match==1){cout<<"Matched value found\n";
}
else {cout<<"No match found\n";}
}
//3rd option
void ModifyValue(){int input1;
cout<<"Enter the position at which you want to modify value\n";
cin>>input1;
cout<<"Enter a value\n";
cin>>f[input1-1];
}
//4th option
void PrintValue(){int i;
for (i=1;i<=100;i++)
{cout<<f[i]<<' ';}
}
//5th option
void PrintSum(){int i,sum;
for(i=1;i<=100;i++)
{sum=f[i]+f[i+1];}
cout<<"Sum is : "<<sum;
}
//starting Function
void menu(){int x;
cout<<"Enter an option: \n";
cout<<"1- Add new value\n2- Search Value\n3- Modify value\n4- Print Value\n5- Print sum of all values\n6- Quit/terminate\n";
cin>>x;
if(x==1){
AddNewValue();
}
else if (x==2){
SearchValue();
}
else if(x==3){
ModifyValue();
}
else if(x==4){
PrintValue();
}
else if(x==5){
PrintSum();
}
else{
}
}
int main(){
int repeater;
do{
menu();
cout<<"Enter 5 to exit or any other key to run the program again :";
cin>>repeater;
}while(repeater != 5);
}

Keep it simple. The function in charge of displaying the menu should only display the menu and return the user's choice.
enum choice
{
ADD_NEW_VALUE,
SEARCH_VALUE,
// ...
QUIT
};
choice menu()
{
choice result = QUIT;
// display menu
// input choice
// (the more I think about it, the more I'd split it in two separate functions)
return result;
}
int main()
{
while (true) {
switch (menu())
{
case ADD_NEW_VALUE: AddNewValue(); break;
// ...
case QUIT: return 0;
}
}
}
This helps menu()'s testing and make it easier to add new options and new features.

If the user selects a correct option, call the menu function again. Otherwise, return control to main. I think this may work.
int menu(){int x;
cout<<"Enter an option: \n";
cout<<"1- Add new value\n2- Search Value\n3- Modify value\n4- Print Value\n5- Print sum of all values\n6- Quit/terminate\n";
cin>>x;
if(x!=1||x!=2||x!=3||x!=4||x!=5) return 0;
if(x==1){
AddNewValue();
}
else if (x==2){
SearchValue();
}
else if(x==3){
ModifyValue();
}
else if(x==4){
PrintValue();
}
else if(x==5){
PrintSum();
}
menu();
}
You could also wrap your code in a do-while loop.
void menu(){
do{
int x;
cout<<"Enter an option: \n";
cout<<"1- Add new value\n2- Search Value\n3- Modify value\n4- Print Value\n5- Print sum of all values\n6- Quit/terminate\n";
cin>>x;
if(x==1){
AddNewValue();
}
else if (x==2){
SearchValue();
}
else if(x==3){
ModifyValue();
}
else if(x==4){
PrintValue();
}
else if(x==5){
PrintSum();
}
}while(x==1||x==2||x==3||x==4||x==5);
}

Related

Program goes into infinite loop, But if removed some functions or lines, it works

A basic student database using classes, I accept
name,
roll number, and
sgpa(cgpa equivalent but out of 10).
I used while loop, and switch case,but if the code for sgpa validation, and code for displaying all students with same sgpa is removed, the program works neatly, but if not, the program goes into continuous loop, the while loop inside the main, as it accepts the options itself and keeps doing it.
The code fails when i accept the sgpa(while taking the student data) or call the displaySGPA fucntion(option 3)
int totalStudents=0;
class database{
float sgpa;
int roll;
string name;
public:
void getSGPA();
void getData(database []);
friend void displaySGPA(int,database []);
};
//Display Students with same SGPA
void displaySGPA(int temp,database students[]){
int i,sameSGPA=0;
for(i=0;i<totalStudents;i++){
if(students[i].sgpa==temp){
sameSGPA+=1;
}
}
if(sameSGPA>1){
cout<<"\nStudents with SGPA "<<temp<<"."<<endl;
for(i=0;i<totalStudents;i++){
if(students[i].sgpa==temp){
cout<<" "<<students[i].roll<<" "<<students[i].name;
}
}
}
else if(sameSGPA==1){
cout<<"Only one student with the SGPA , "<<temp<<". :"<<endl;
for(i=0;i<totalStudents;i++){
if(students[i].sgpa==temp){
cout<<" "<<students[i].roll<<" "<<students[i].name;
break;
}
}
}
else{
cout<<"No Student with given SGPA."<<endl;
}
}
void database :: getData(database students []){
cout<<"\nEnter Name : ";
cin>>name;
cout<<"Enter Roll. ";
cin>>roll;
getSGPA();
}
//SGPA validation
void database :: getSGPA(){
int x=1,temp;
while(x==1){
cout<<"Enter SGPA : ";
cin>>temp;
if(temp<=10){
sgpa=temp;
break;
}
else{
cout<<"Please enter a valid SGPA.";
}
}
}
//main Loop
int main() {
int x,temp;
database students[50];
while (x!=5){
cout<<"\n1.Enter a New Student.\n3.Display students with same SGPA.\n5.Exit.\n\nYour Choice : ";
cin>>x;
switch(x){
case 1:
students[totalStudents].getData(students);
totalStudents++;
break;
case 3:
cout<<"\nEnter the SGPA.";
cin>>temp;
displaySGPA(temp,students);
break;
case 5:
cout<<"Exiting the program.....";
break;
default:
cout<<"Please select a valid option."<<endl;
}
}
}
I found the bug, it was a type conversion bug, i was accepting a float value but passing it as a int,just worked, don't know why.But thanks for each comment and suggestion.

Check if array is empty or not C++

Please tell me how to check whether array is empty on not?
see my code after the step of code modify comment.I want a message "Sorry no value added so far".
#include<iostream>
using namespace std;
int count=0;
//----------------------------------------------------------//
//---------menu items list start from this position---------//
//----------------------------------------------------------//
void menu(int n){cout<<"\nEnter an option: \n";
cout<<"1- Add new value\n2- Search Value\n3- Modify value\n4- Print Value\n5- Print sum of all values\n6- Quit/terminate\n";
}
//-----------------------------------------------------------//
//---------Funtion to add new values starts from here--------//
//-----------------------------------------------------------//
void AddNewValue(int a[]){
cout<<"Enter a value\n";
cin>>a[count]; //taking input to array
count++;
}
//------------------------------------------------------------------------//
//---------Function to search a value from array starts from here---------//
//------------------------------------------------------------------------//
void SearchValue(int a[]){
int num,jawad=0;
cout<<"Enter a number to search\n";
cin>>num;
for(int starter=0;starter<count;starter++){ //starting loop from 1st value of array
if (num==a[starter])
jawad=1; //switching jawad from 0 to 1 if value found
}
if(jawad==1)
cout<<"value exists at "<<count<<"th position\n";
else cout<<"Value does not exist";
}
//-------------------------------------------------------------------//
//---------Function to modify value in array start from here---------//
//-------------------------------------------------------------------//
void ModifyValue(int a[]){
int modification,position;
cout<<"Enter the position of a number to modify";
cin>>position;
cout<<"Enter a number to modify";
cin>>modification;
a[position-1]=modification; //calculating index from enterd value and placing that equal to new number
}
//-----------------------------------------------------------//
//---------Function to Print values starts from here---------//
//-----------------------------------------------------------//
void PrintValue(int a[]){
cout<<"The stored values are : ";
for(int c=0;c<count;c++) //start loop and tak out all the values then print them
{cout<<a[c]<<' ';
if (a[c]==0)
cout<<"jawad adil";
}
}
//------------------------------------------------------------------------------//
//----------Function to Take sum of the values of array starts from here--------//
//------------------------------------------------------------------------------//
void PrintSum(int a[]){
int r=0,sum=0;
cout<<"The sum of all the values is : ";
while(r<count){
sum=sum+a[r]; //taking sum of all the values using loop
r=r+1;
}
cout<<sum<<'\n';
}
//---------------------------------------------//
//----------main body starts from here---------//
//---------------------------------------------//
int main(){
int n;
int a[100];
while(n!=6){
menu(n);
cin>>n;
if (n==1){
AddNewValue(a); //calling functions using if else statments
}
else if(n==2){
SearchValue(a);
}
else if(n==3){
ModifyValue(a);
}
else if(n==4){
PrintValue(a);
}
else if(n==5){
PrintSum(a);
}}
}
how can I do that? I am doing but it is not working.
You should add a "check" in your "modify" function.
Original:
void ModifyValue(int a[]){
int modification,position;
cout<<"Enter the position of a number to modify";
cin>>position;
cout<<"Enter a number to modify";
cin>>modification;
a[position-1]=modification;
With "check":
void ModifyValue(int a[]){
//Check
if(count == 0)
{
cout << "Sorry no value added so far";
return; //Exit from function
}
int modification,position;
cout<<"Enter the position of a number to modify";
cin>>position;
cout<<"Enter a number to modify";
cin>>modification;
a[position-1]=modification;
}
Also I recommend you to use switch instead of "if else if"
if (n==1){
AddNewValue(a); //calling functions using if else statments
}
else if(n==2){
SearchValue(a);
}
else if(n==3){
ModifyValue(a);
}
else if(n==4){
PrintValue(a);
}
else if(n==5){
PrintSum(a);
}
like:
switch (n)
{
case 1:
AddNewValue(a);
break;
case 2:
SearchValue(a);
break;
case 3:
ModifyValue(a);;
break;
//And so on...
default:
cout << "Unknown option";
}
Also in this code you don't need any arguments in
void menu(int n)
So you can make
void menu()
instead.
Also I recommend you to place whitespaces between operands and operators (words)
cout << "Enter a value\n";
cin >> a[count]; //taking input to array
count++;
instead
cout<<"Enter a value\n";
cin>>a[count]; //taking input to array
count++;

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?

How to Return a structure

How Can I return all the structures when i choose 7.Logout after i insert a record from the Admin menu, and if i return to the admin menu, i'll see the record again.
For Example
User:Admin
Pass:Admin
then i choose 2.Insert Product after that Ill go choose 1.display , after that i 7.log out. now i want to login again as Admin but i want to see all the data again.please help this is our thesis project.
#include <iostream>
#include <string>
#include <iomanip>
#include <conio.h>
using namespace std;
struct product{
string pname,pid;
int qnty;
double price;
product *ptr;
};
//Function Declaration
void Menu(string username);
void InsertProduct();
void DeleteProduct();
void DisplayProduct();
void SearchProduct();
void PurchaseProduct();
//
product *head;
int main() //Account Login
{
int pw=0,n;
char pwc=' ';
string username,password;
cout<<"\n ==============================================================================="<<endl<<endl;
cout<<"\t\t\t LICA'S GROCERY STORE"<<endl<<endl;
cout<<" ==============================================================================="<<endl<<endl;
cout<<"\t\t\t Username: ";
getline(cin, username);
cout<<"\n\t\t\t Password: ";
do
{
pwc=getch();
if(pwc==13||pwc==' ')
{
break;
}
cout<<"*";
password+=pwc;
pw++;
}
while(pwc!=13||pwc!=' ');
n=username.length();
for(int a=0; a!=n; a++)
{
if(isupper(username.at(a)))
{
username.at(a) = tolower(username.at(a));
}
}
if(username=="admin" && password=="Admin")
{
system("CLS");
cout<<"\n ==============================================================================="<<endl<<endl;
cout<<"\t\t\t\t WELCOME ADMIN!"<<endl<<endl;
cout<<" ==============================================================================="<<endl<<endl;
Menu(username);
return main();
}
else if(username=="cashier" && password=="Cashier")
{
system("CLS");
cout<<"\n ==============================================================================="<<endl<<endl;
cout<<"\t\t\t\t WELCOME CASHIER!"<<endl<<endl;
cout<<" ==============================================================================="<<endl<<endl;
Menu(username);
}
else
{
system("CLS");
cout
<<"\n\t\t Invalid Username or Password. Please Try Again"<<endl;
return main();
}
system("pause");
return 0;
}
//
//
//
//
//
void Menu(string username)
{
head=NULL;
int menu;
if(username=="admin")
{
do
{
cout
<<"\t MENU: "
<<"\n\n\t\t\t A. FILE MAINTENANCE" <<endl
<<"\n\t\t\t\t 1. Display All Products"<<endl
<<"\t\t\t\t 2. Insert New Product"<<endl
<<"\t\t\t\t 3. Delete A Product" <<endl
<<"\t\t\t\t 4. Search A Product"<<endl
<<"\n\t\t\t B. SALES MODULE"<<endl
<<"\n\t\t\t\t 5. Cashier"<<endl
<<"\t\t\t\t 6. Print Receipt."<<endl
<<"\n\t\t\t C. EXIT"<<endl
<<"\n\t\t\t\t 7. Log Out"<<endl;
cout<<"\n\t Choose an option (1 to 7 only): ";
cin>>menu;
cin.ignore();
switch(menu)
{
case 1:
cout<<"\n ============================================================================="<<endl<<endl;
cout<<"\t\t\t DISPLAY ALL PRODUCTS"<<endl<<endl;
cout<<" ============================================================================="<<endl<<endl;
DisplayProduct();
system("pause");
system("CLS");
break;
case 2:
cout<<"\n ============================================================================="<<endl<<endl;
cout<<"\t\t\t INSERT NEW PRODUCT"<<endl;
cout<<" ============================================================================="<<endl<<endl;
InsertProduct();
break;
case 3:
cout<<"\n ============================================================================="<<endl<<endl;
cout<<"\t\t\t DELETE A PRODUCT"<<endl;
cout<<" ============================================================================="<<endl<<endl;
DeleteProduct();
break;
case 4:
cout<<"\n ============================================================================="<<endl<<endl;
cout<<"\t\t\t SEARCH A PRODUCT" <<endl;
cout<<" ============================================================================="<<endl<<endl;
SearchProduct();
break;
case 5:
cout<<"\n ============================================================================="<<endl<<endl;
cout<<"\t\t\t PURCHASE PRODUCTS"<<endl;
cout<<" ============================================================================="<<endl<<endl;
PurchaseProduct();
case 7:
cout<<"\n\n THANK YOU ADMIN!"<<endl<<endl;
break;
default:
cout<<"\n\n INVALID INPUT!"<<endl<<endl;
}
}while(menu!=7);
}
else
{
cout
<<"Choose an Option"
<<"\n1.Sales Module"
<<"\n2.Exit"<<endl;
cin>>menu;
switch(menu)
{
case 1:
cout<<"Sales Module";
break;
case 2:
cout<<"Exit!";
break;
default:
cout<<"Invalid Input!";
}
}
}
void InsertProduct()
{
product *newproduct;
newproduct=new product;
cout<<"\n\n\tEnter Product Name:";getline(cin,newproduct->pname);
cout<<"\n\tEnter Product Quantity:";cin>>newproduct->qnty;
cout<<"\n\tEnter Product ID:";cin>>newproduct->pid;
cout<<"\n\tEnter Product Price:";cin>>newproduct->price;
cin.ignore();
newproduct->ptr=NULL;
if(head==NULL)
head=newproduct;
else
{
product *lastproduct;
lastproduct=head;
while(lastproduct->ptr!=NULL)
lastproduct=lastproduct->ptr;
lastproduct->ptr=newproduct;
}
cout<<"\n\tProduct is inserted"<<endl;
system("pause");
system("CLS");
}
void DeleteProduct()
{
DisplayProduct();
product *current,*previous;
current=head;
int x;
if (current==NULL)
{
cout<<"\n\t\tNo Products Found.";
}
else
{
cout<<"\n\t\tEnter Product No. to delete:";
cin>>x;
int i=1;
if(x==1)
{
head=current->ptr;
delete current;
cout<<"\n\t\tProduct is deleted";
DisplayProduct();
}
else
{
while(i<x&&current!=NULL)
{
previous=current;
current=current->ptr;
i=i++;
}
if(current==NULL)
{
cout<<"\n\t\tProduct does not Exist";
}
else
{
previous->ptr=current->ptr;
delete current;
cout<<"\n\t\tProduct is deleted";
DisplayProduct();
}
}
}
system("pause");
system("CLS");
}
void DisplayProduct()
{
product *current;
current=head;
int i=1;
cout<<setiosflags(ios::left);
while(current!=NULL)
{
cout<<"\n\t\t"<<setw(4)<<i;
cout<<setw(25)<<current->pname<<setw(3)<<current->qnty <<setw(3)<<current->pid <<setw(3)<<current->price;
current=current->ptr;
i++;
}
}
void SearchProduct()
{
string sid;//Name to search
product *current;
current=head;
if (current==NULL)
cout<<"\n\t\tNo Products Found";
else
{
cout<<"\n\t\tEnter product to search: ";
cin>>sid;
int i=1;
while(sid.compare(current->pid))
{
current=current->ptr;
if (current==NULL)
break;
i++;
}
if(current!=NULL)
cout<<"\n\t\t"<<current->pid<<" is Product No."<<i;
else
cout<<"\n\t\t"<<sid<<" is not in the list.";
DisplayProduct();
cout<<endl;
}
system("pause");
system ("CLS");
}
void PurchaseProduct()
{
}
Your data is in memory until you save it to hardk disk, so you need to implement some mechanism for doing that.
You can choose among several options such as using data bases, plain files(XML, YAML, JSON, etc ...) and object searialization wich I think it's your best option right now. There are several libraries out there for doing that, but for start I recommend you use this tutorial. Then move to A practical guide to C++ serialization.
I recommend serialization because I realized you are just starting with C++. And others options like data bases and formated files(xml, Yaml, etc...) require more complex code.
Have fun!!! After you read all this stuff and (try to put it in practice), if you still can't solve your problem, come back here, and we will happy to help you.

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

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.