How to "restart" a program - c++

I am a beginner that has been coding in c++ for a few weeks now. I have written a my program to have a menu from which a user selects options to perform different tasks. I have 2 questions: firstly how do I make it so the user gets sent back to the menu after performing a task and secondly, how do I make it so when the user is assigning variables (is that what you call it?) the numbers stay on the same line?
#include <iostream>
using namespace std;
int main() {
int choice;
float no0,no1,no2,no3,sum0,ave,pi,rad,areaC,base,height,areaT;
pi=3.142;
cout<<"______________________________________________\n";
cout<<"| MENU |\n";
cout<<"|--------------------------------------------|\n";
cout<<"|1. Calculate the average of 4 numbers. |\n";
cout<<"|2. Calculate the area of a circle. |\n";
cout<<"|3. Calculate the area of a triangle. |\n";
cout<<"|4. Print 'Hello World! |\n";
cout<<"|--------------------------------------------|\n";
cout<<"Enter a number to make a selection... ";
cin>>choice;
switch (choice)
{
case 1:
cout<<"Enter 4 numbers to find their average: ";
cin>>no0>>no1>>no2>>no3;
sum0=no0+no1+no2+no3;
ave=sum0/4;
cout<<"The average of your 4 numbers is: "<<ave<<"\n";
break;
}
switch (choice)
{
case 2:
cout<<"Enter the radius of a cirlce to find its area: ";
cin>>rad;
areaC=pi*rad*rad;
cout<<"The area of your circle is:"<<areaC<<"\n";
break;
}
switch (choice)
{
case 3:
cout<<"Enter the base and height of a triangle to find its area.""\n";
cout<<"Base: "; cin>>base;
cout<<"Height: "; cin>>height;
areaT=base*height*0.5;
cout<<"The area of your triangle is: "<<areaT<<"\n";
break;
}
switch (choice)
{
case 4:
cout<<"Hello World!";
}
return 0;
}

You can add an endless loop that will return your user to the beginning of the program indefinitely. If you want it to stop, you can add a case that sets active to false.
I also fixed your switch cases. As someone mentioned, it's not necessary to switch for each case - the program will automatically find the correct path.
Do something like this:
#include <iostream>
using namespace std;
int main() {
bool active = true;
while(active)
{
int choice;
float no0,no1,no2,no3,sum0,ave,pi,rad,areaC,base,height,areaT;
pi=3.142;
cout<<"______________________________________________\n";
cout<<"| MENU |\n";
cout<<"|--------------------------------------------|\n";
cout<<"|1. Calculate the average of 4 numbers. |\n";
cout<<"|2. Calculate the area of a circle. |\n";
cout<<"|3. Calculate the area of a triangle. |\n";
cout<<"|4. Print 'Hello World! |\n";
cout<<"|5. Quit. |\n";
cout<<"|--------------------------------------------|\n";
cout<<"Enter a number to make a selection... ";
cin>>choice;
switch (choice)
{
case 1:
cout<<"Enter 4 numbers to find their average: ";
cin>>no0>>no1>>no2>>no3;
sum0=no0+no1+no2+no3;
ave=sum0/4;
cout<<"The average of your 4 numbers is: "<<ave<<"\n";
break;
case 2:
cout<<"Enter the radius of a cirlce to find its area: ";
cin>>rad;
areaC=pi*rad*rad;
cout<<"The area of your circle is:"<<areaC<<"\n";
break;
case 3:
cout<<"Enter the base and height of a triangle to find its area.""\n";
cout<<"Base: "; cin>>base;
cout<<"Height: "; cin>>height;
areaT=base*height*0.5;
cout<<"The area of your triangle is: "<<areaT<<"\n";
break;
case 4:
cout<<"Hello World!";
break;
case 5:
active = false; // Could even just return 0 here
break;
} // End Switch
} // End Loop
return 0;
}

I recommend use an alternative the cycle for reset your program, also group the different case in the same switch for example:
#include <iostream>
using namespace std;
int main() {
float no0,no1,no2,no3,sum0,ave,pi,rad,areaC,base,height,areaT;
pi=3.142;
int choice;
do{
cout<<"______________________________________________\n";
cout<<"| MENU |\n";
cout<<"|--------------------------------------------|\n";
cout<<"|1. Calculate the average of 4 numbers. |\n";
cout<<"|2. Calculate the area of a circle. |\n";
cout<<"|3. Calculate the area of a triangle. |\n";
cout<<"|4. Print 'Hello World! |\n";
cout<<"|5. Quit. |\n";
cout<<"|--------------------------------------------|\n";
cout<<"Enter a number to make a selection... ";
cin>>choice;
switch (choice){
case 1:
cout<<"Enter 4 numbers to find their average: ";
cin>>no0>>no1>>no2>>no3;
sum0=no0+no1+no2+no3;
ave=sum0/4;
cout<<"The average of your 4 numbers is: "<<ave<<"\n";
break;
case 2:
cout<<"Enter the radius of a cirlce to find its area: ";
cin>>rad;
areaC=pi*rad*rad;
cout<<"The area of your circle is:"<<areaC<<"\n";
break;
case 3:
cout<<"Enter the base and height of a triangle to find its area.""\n";
cout<<"Base: "; cin>>base;
cout<<"Height: "; cin>>height;
areaT=base*height*0.5;
cout<<"The area of your triangle is: "<<areaT<<"\n";
break;
case 4:
cout<<"Hello World!\n";
break;
case 5:
cout<<"Bay\n";
break;
default:
cout<<"Wrong selection\n";
break;
} // End Switch
//If you want clear the screen you can use the instruction:cout<<"\033[2J\033[1;1H";
}while(choice != 5); // End Loop
return 0;
}

Related

How to make functions for reverse number guessing game?

For my assignment, I need to make a program that guesses the user's number, between 1-19 inclusively, within 5 tries. For each try, the user inputs if the number is: a) correct, b) too high, or c) too low
We are supposed to define two functions:
The first is a function that takes a number (int) as a parameter and outputs the prompt to the user that guesses that number (tells the user "Is this your number: <guess>") and shows them a menu that explains how to enter correct, high, or low.
The second function is supposed to calculate the next guess after being told if it is too high or too low.
I was able to accomplish this with nested switch statements, but I am having trouble trying to come up with the second function.
Any help is appreciated. I will try to attach my first program with the switch statements. I assume I need to generate a random number with the min and max, but I'm not sure how to do it.
#include<iostream>
using namespace std;
int main()
{
int guess = 10;
int input = 0;
cout<<"Is this your number: "<< guess<<endl;
cout<< "Correct? (1), High?(2), Low(3)"<<endl;
cin>> input;
switch(input) {
case(1):
cout<< "Thanks for playing";
break;
case(2):
guess = 5;
cout<<"Is this your number: "<< guess<<endl;
cout<< "Correct? (1), High?(2), Low(3)"<<endl;
cin>> input;
switch(input){
case(1):
cout<< "Thanks for playing";
break;
case(2):
guess = 3;
cout<<"Is this your number: "<< guess<<endl;
cout<< "Correct? (1), High?(2), Low(3)"<<endl;
cin>> input;
switch (input){
case(1):
cout<< "Thanks for playing";
break;
case(2):
guess = 2;
cout<<"Is this your number: "<< guess<<endl;
cout<< "Correct? (1), High?(2), Low(3)"<<endl;
cin>> input;
switch(input){
case(1):
cout<< "Thanks for playing";
break;
case (2):
guess = 1;
cout<< "Your guess was: "<<guess<<endl;
break;
case (3):
cout<< "Cheater..."<<endl;
break;
}
break;
case(3):
guess = 4;
cout<< "Your guess was: "<<guess<<endl;
break;
}
break;
case(3):
guess = 7;
cout<<"Is this your number: "<< guess<<endl;
cout<< "Correct? (1), High?(2), Low(3)"<<endl;
cin>> input;
switch (input){
case (1):
cout<< "Thanks for playing";
break;
case(2):
guess = 6;
cout<< "Your guess was: "<<guess<<endl;
break;
case(3):
guess = 8;
cout<<"Is this your number: "<< guess<<endl;
cout<< "Correct? (1), High?(2), Low(3)"<<endl;
cin>> input;
switch (input){
case (1):
cout<< "Thanks for playing";
break;
case(2):
cout<<"Cheater..."<<endl;
case(3):
guess = 9;
cout<< "Your guess was: "<< guess<<endl;
break;
}
}
break;
}
break;
case(3):
guess = 15;
cout<<"Is this your number: "<< guess<<endl;
cout<< "Correct? (1), High?(2), Low(3)"<<endl;
cin>> input;
switch(input){
case(1):
cout<< "Thanks for playing";
break;
case(2):
guess = 13;
cout<<"Is this your number: "<< guess<<endl;
cout<< "Correct? (1), High?(2), Low(3)"<<endl;
cin>> input;
switch (input){
case(1):
cout<< "Thanks for playing";
break;
case(2):
guess = 12;
cout<<"Is this your number: "<< guess<<endl;
cout<< "Correct? (1), High?(2), Low(3)"<<endl;
cin>> input;
switch(input){
case(1):
cout<< "Thanks for playing";
break;
case (2):
guess = 11;
cout<< "Your guess was: "<<guess<<endl;
break;
case (3):
cout<< "Cheater..."<<endl;
break;
}
break;
case(3):
guess = 14;
cout<< "Your guess was: "<<guess<<endl;
break;
}
break;
case(3):
guess = 17;
cout<<"Is this your number: "<< guess<<endl;
cout<< "Correct? (1), High?(2), Low(3)"<<endl;
cin>> input;
switch (input){
case (1):
cout<< "Thanks for playing";
break;
case(2):
guess = 16;
cout<< "Your guess was: "<<guess<<endl;
break;
case(3):
guess = 18;
cout<<"Is this your number: "<< guess<<endl;
cout<< "Correct? (1), High?(2), Low(3)"<<endl;
cin>> input;
switch (input){
case (1):
cout<< "Thanks for playing";
break;
case(2):
cout<<"Cheater..."<<endl;
case(3):
guess = 19;
cout<< "Your guess was: "<< guess<<endl;
break;
}
}
break;
}
break;
}
return 0;
}
Try this:
#include <iostream>
using namespace std;
#define elif else if
void guessf(int guess) {
cout << "Is this your number: " << guess << endl << "Correct? (1), High?(2), Low(3)" << endl;
}
int main(){
unsigned int range = 10, guess = 10, input = 0, i = 0;
while (i < 5 && input != 1) {
guessf(guess);
cin >> input;
if (range > 1)
range /= 2;
else
range = 1;
if (input == 1)
cout << "Thanks for playing";
elif (input == 2)
guess -= range;
else
guess += range;
}
}
What this does: the guessf() is pretty simple so we move on to the main(),the range variable is what it will be added or subtracted from the guess on each try, then, until your program does 5 tries or the guess is correct, ask user if it is correct, high or low, if it is correct cout << "Thanks for playing";, if the guess is high subtract the range and if the guess is low add the rangeto the guess. Also bcs we deal with int, the minimum value of range must be 1, bcs if it is lower nothing will ever be added or subtracted from the guess. This technique is at least something similar to "Binary Search"
If you want to remove elif, remove #define elif else if and replace elif with else if( else and if in the same line)
Also by 2 functions, you mean 2 including the main or without? This is an important thing to know
Here are some observations:
The problem set consists of numbers from 1 up to 19 i.e. range [1, 19].
The given number needs to be searched/guessed in this range.
The range is fixed i.e. it will always be [1, 19]. That means it's a sorted range.
The number of tries to guess the number is 5.
So, given the above characteristics, the Binary Search algorithm would provide an optimal solution i.e.:
Range = [1, 19]
No. of tries = 5
Worst-case performance of Binary search algorithm = O(log n)
i.e. Range = 19, O(log n) = O(log 19) = 4.25 = ~5 tries
You can do some research on the Binary Search algorithm to get familiar with it. The rest would be your logic of maintaining high, low and mid points. And, you don't need random numbers for this!
You would be using your own variation of the Binary search algorithm that guesses the number by adjusting the problem set i.e. range where the number may exist.
As far as your two functions are concerned:
The first function would show the menu and input the number to be guessed.
The second function would perform the guessing.
For the rest of the boilerplate logic, you can implement that in your main() function.
Here's a general breakdown of your code (just a synopsis, assuming you're using C++98 or C++03):
int showMenuAndInputNumber() { /* ... */ }
int guessNumber(const int n) { /* ... */ }
int main()
{
const int n = showMenuAndInput();
// validate if n is in the range [1, 19]
// given the search sorted range and the valid number,
// then using Binary search you'll need max 5 tries
// so, you don't need to keep track of the tries
// but, for simplicity, you can use tries
const int tries = 5;
for ( int t = 0; t < tries; ++t )
{
// guess the number here
// adjust the range either right or left
// according to your own Binary search algorithm's variation
}
return 0;
}
This is not meant to be a ready-made solution to your problem. This is just to provide some guidelines.
Hope this helps!

Loops in C++ to Check Wrong Input and to Start Program Again if user enters Correct Input

I am new to c++. I have given assignment in which i have to calculate grades and ask input from the user. If he enter wrong input i have to start program again. If the user enters correct input i have to process data and again ask if he wants to check for another calculation.I have written this code so far. I don't know how to loop back again in the program if the user enters wrong input and to start program again if it is successful. Please Give me guidance over it. Thanks.
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
//Declaring Variable
char choice;
char input;
//Promptin User to Enter his/her Choice
cout<<"Enter C or c for Computer Science: \n" ;
cout<<"Enter S or s for Software Engineering: \n";
cout<<"Enter T or T for Telecom Engineering: \n";
cout<<"Select any option from the above Menu: ";
cin>>input;
if (input != 'c' || input != 'C'){
cout<<"Invalid input! Enter the correct input option again";
}else if (input != 's' || input != 'S' ){
cout<<"Invalid input! Enter the correct input option again";
}else if (input != 't' || input != 'T' ){
cout<<"Invalid input! Enter the correct input option again";
}else if (input == 'a' || input == 'A'){
}
system("pause");
return 0;
}
You can do it using a simple do while loop:
bool valid_input = false;
do
{
// Code to read and validate the input...
} while (valid_input == false);
If the input is valid, then you set valid_input to true and the loop will end.
On an unrelated note, if you don't case about upper- or lower-case, use e.g. std::tolower so you only have to compare the letter once. E.g. std::tolower(input)
!= 'c'.
Here is the code that will prompt the user for answer as long as the answer is defined withing switch statement. ans is a variable to hold a character either 1 or 0 corresponds to the user's input (defined in switch cases or not). If defined, then ans gets 1 other wise it gets value 0. Do While loop repeats while ans is 1 (defined within switch statement).
#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
char input;
char ans; //correct answer, incorrect answer
do {
cout<<"Enter C or c for Computer Science: \n" ;
cout<<"Enter S or s for Software Engineering: \n";
cout<<"Enter T or T for Telecom Engineering: \n";
cout<<"Select any option from the above Menu: ";
cin>>input;
switch (input){
case 'S':
ans = 1;
break;
case 's':
ans = 1;
break;
case 'C':
ans = 1;
break;
case 'c':
ans = 1;
break;
case 'T':
ans = 1;
break;
case 't':
ans = 1;
break;
default:
ans = 0;
}
} while (ans);
return 0;
}
User input handling is very common and can normally use similar patterns.
Basically, you re-ask for the input. You handle the valid choices and break out of the loop and you show an error when the choice is invalid and let the loop ask the input again.
Remark1: by not using switch-case here, I can break out of the loop immediately. I break immediately to avoid specifying the conditions twice or using flags, that is also why I use a loop without end-condition.
Remark2: std::flush is used to input on the prompt line. It makes sure that the prompt is shown before waiting for input.
char inp = 0;
while (true) {
std::cout << "Give input (a, b): " << std::flush;
std::cin >> inp;
inp = std::tolower(inp);
if (inp == 'a') {
std::cout << 'a\n';
break;
}
if (inp == 'b') {
std::cout << 'b\n';
break;
}
std::cout << "invalid choice (" << inp << ")";
}
The invalid choice handling can be done a bit more generic by this function, but the handling of the valid choices must still be done locally:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
char askInputChoice(const std::string& prompt, const std::vector<char>& valid)
{
char inp = 0;
while (true) {
std::cout << prompt << ": " << std::flush;
std::cin >> inp;
inp = std::tolower(inp);
if (std::find(valid.begin(), valid.end(), inp) != valid.end()) {
break;
}
std::cout << "invalid choice (" << inp << ")\n";
}
return inp;
}
int main()
{
char inp = askInputChoice("Give input (a, b)", std::vector<char>{'a','b'});
switch (inp) {
case 'a':
std::cout << "a\n";
break;
case 'b':
std::cout << "b\n";
break;
}
}
To restart the program, put it in a while loop, add a choice to quit ('q') and break when that choice is given.
Thanks Guys for All Your Support. Actually it is my First Program in C++ and sorry i have used the word guidance. Actually i have compiled it successfully. Kindly Check my program i know u do not need to but i want to know if i can add more into it to improve it.
#include <cstdlib>
#include <iostream>
#include <conio.h>
using namespace std;
int main(int argc, char *argv[])
{
//Declaring Variable
char choice;
char input;
int addTest = 0, matricMarks = 0 , interMarks = 0 , result = 0;
start: //Label
system("cls"); // Clear the Screen
//Prompting User to Enter his/her Choice
cout<<"Please Select the Degree Programme in which you are interested in to take Addmission: ";
cout<<"\nEnter C or c for Computer Science: "<<endl ;
cout<<"Enter S or s for Software Engineering: "<<endl;
cout<<"Enter T or t for Telecom Engineering: \n"<<endl;
cout<<"\nSelect any option from the above Menu: ";
cin>>input;
//Switch Statement Started
switch(input){
//Case C Started
case 'c':
case 'C':
{
cout<<"Enter your Marks in Addmission Test: ";
cin>>addTest;
cout<<"Enter your Marks in Matric Degree: ";
cin>>matricMarks;
cout<<"Enter your Marks in Intermediate Degree: ";
cin>>interMarks;
result = (addTest * 0.20)+(matricMarks * 0.30)+(interMarks * 0.50);
if (result >= 70)
{
cout<<"\nCongratulations! You are eligible for the Computer Science degree program :)"<<endl;
}
else
{
cout<<"Sorry you Do not qualify for Computer Science Degree Programme: "<<endl;
system("pause");
}
break;
}//Case C Closeed
//Case s Started
case 's':
case 'S':
{
cout<<"Enter your Marks in Addmission Test: ";
cin>>addTest;
cout<<"Enter your Marks in Matric Degree: ";
cin>>matricMarks;
cout<<"Enter your Marks in Intermediate Degree: ";
cin>>interMarks;
result = (addTest * 0.20)+(matricMarks * 0.30)+(interMarks * 0.50);
if (result >= 85)
{
cout<<"\nCongratulations! You are eligible for the Software Enginnering degree program :)"<<endl;
}
else
{
cout<<"\nSorry! you Do not Qualify for Software Engineering Degree: "<<endl;
system("pause");
}
break;
}//Case S Closed
//Case t Started
case 't':
case 'T':
{
cout<<"Enter your Marks in Addmission Test: ";
cin>>addTest;
cout<<"Enter your Marks in Matric Degree: ";
cin>>matricMarks;
cout<<"Enter your Marks in Intermediate Degree: ";
cin>>interMarks;
result = (addTest * 0.20)+(matricMarks * 0.30)+(interMarks * 0.50);
if (result >= 80)
{
cout<<"\nCongratulations! You are eligible for the Telecom Engineering degree program :)"<<endl;
}
else
{
cout<<"Sorry you Do not Qualify for Telecom Enginnering Degree Programme: "<<endl;
system("pause");
}
break;
}//Case t Closed
//Default Case Started
default:
{
cout<<"\nInvalid input! Enter the correct option again: \n";
system("pause");
goto start; //Jump To Label Start
}//Deafult Case Closed
}// Switch Statement Close
//do while Loop Started
do{
cout<<"\nDo you want to check your eligibility in some other degree program y/n? : ";
cin>>choice;
if (choice=='Y'||choice=='y')
{
goto start; //jump to Label start:
}
else if (choice=='N'||choice=='n')
{
break;
}
}while(choice == 'y' || choice == 'Y');
//Do while Loop Closed
system("pause");
return 0;
}

Reading strings and integers into arrays from .txt file

I am a novice programmer and I'm having trouble with one of my exercises. I need to create a program that reads the student information (SSN, First & last name, test score) from a .txt file called "students.txt", and then uses four global parallel arrays to store the student information. I'm required to use an int array to store SSN, a string array to store first names, a string array to store last names, and a double array to store scores. The operations include listing the students' info like this exactly how it appears:
SSN Last-Name First-Name Score
628130189 James, Paul 92.0
237698211 Cook , Daniel 86.0
201895367 Garza, Melessa 78.0
491066285 Barbara, Jessica 62.0
168606868 Bruce, Elizabeth 90.0
378205732 Lee, Sarah 91.5
118453900 Brian, David 87.0
583192186 Garza, Cody 92.0
226665118 Lewis, Gage 78.0
175382843 Collins, James 69.5
816231095 White, Ann 88.5
376651608 Jackson, Mark 72.0
508234567 Freeman, Mark 86.0
763211099 William, Jack 52.0
286204723 Rodriguez, John 69.5
But of course, the .txt file is just SSN First-name last-name and score unaligned and separated by comas. Then I have to display the student with the highest score, and then the lowest, and the average of all scores using "void". I just dont know how to get it to read the file in the first place and make the data so that it's organized into columns.
Also...I have to report an error message and exit the program immediately if the file cannot be found? Otherwise, the program should display a main menu as follows to allow the user to complete the listed
operations.
Here's what I have so far:
#include <iostream>
#include<iomanip>
#include<fstream>
using namespace std;
void mainmenu();
/*
void sort_name();();
void sort_ssn();
void sort_score ();
*/
void average();
void lowest_score();
void highest_score();
void open_file();
const int totNum = 15; //my global variables
int ssn[totNum];
string fname [totNum];
string lname [totNum];
double score [totNum];
int main ()
{
char choice;
ifstream fin;
fin.open("students.txt")
for (1=0; i <= totNum; i++)//this is where I'm stuck
{
?????
}
do
{ mainmenu(); //calling main menu funtion
cin >> choice;
cin.ignore (10, '\n'); //spacing
switch(choice) // switch statment for multiple cases for flexibility
{
case 'l':
case 'L':
case '1': open_file(); break;
/*
case 'h':
case 'H':
case '2': highest_score(); break;
case 'o':
case 'O':
case '3': lowest_score(); break;
case 'a':
case 'A':
case '4': average(); break;
case 's':
case 'S':
case '5': sort_ssn(); break; //operation 5-7 is a bonus work
case 'n':
case 'N':
case '6': sort_name(); break;
case 'c':
case 'C':
case '7': sort_score();break;
*/
case 'e':
case 'E':
case '0': break;
default: cout << "Wrong choice!" << endl; break;
}
cout << endl;
} while(choice != '0'); // && choice !='E' && choice!='e')
}
void mainmenu() //output main menu
{
cout << "Main Menu (Assignment 8)" << endl;
cout << "1. List students' infromation (L)" << endl;
/*
cout << "2. Find the highest score (H)" << endl;
cout << "3. Find the lowest score (O)" << endl;
cout << "4. Calculate the average score (A)" << endl;
cout << "5. Sort students by SSN (S)" << endl;
cout << "6. Dort students by name (N)" << endl;
cout << "7. Sort students by score (C)" << endl;
*/
cout << "0. Exit" << endl;
cout << "Please select an option: ";
}
it doesn't make any sense now but that's why I'm desperate for help...

Passing value between functions in C++

I'm making a program for car company which has only 6 Salesman. The program will ask the user to input the name of each salesmen and his monthly salary, input the number of cars he sold in a month, as well as the brand and price of each car. The program will display the monthly income of each salesman (salary + commission), the average monthly income of the salesmen, the name(and income) of the salesman who has the highest income, the name (and income)of the salesman with the lowest income, the number of cars sold for each brand and the most popular
brand.
I'm stuck at passing the value of totalCommission from Salesman1() and Salesman2(). Another problem is, i don't know if i can CIN a string into an array named SalesmanName. Here is what i have done so far.
int main()
{
int cycle=1;
int SalesMan1(),SalesMan2();
do
{
switch(cycle)
{
case 1: SalesMan1(); cycle++; break;
case 2: SalesMan2(); cycle++; break;
/*case 3: SalesMan3(); cycle++; break;
case 4: SalesMan4(); cycle++; break;
case 5: SalesMan5(); cycle++; break;
case 6: SalesMan6(); cycle++; break;*/
default: cout<<"Printing out reports"<<endl;
system("\npause");
}
}while(cycle<=6);
return 0;
}
int SalesMan1()
{
char NameOne[40];
int numCar=1,carSold,carType,audiSold=0,bmwSold=0,mbenzSold=0;
double salary,carPrize,commission,totalCommission,allMonthlyIncome;
cout<<"Name of 1st Salesman:"<<endl;
cin.getline(NameOne,39);
cout<<"\nMonthly Salary: RM";
cin>>salary;
cout<<"\nNumber of car sold in a month: ";
cin>>carSold;
system("CLS");
do{
cout<<"\nEnter type of car sold as below: "<<endl;
cout<<"\n1-Audi"<<endl;
cout<<"2-BMW"<<endl;
cout<<"3-Mercedes Benz"<<endl;
cout<<"\nCar Type:";
cin>>carType;
switch(carType)
{
case 1:
cout<<"\nEnter the price sold: RM";
cin>>carPrize;
commission=0.02*carPrize;
totalCommission+=commission;
audiSold++;
system("CLS");
break;
case 2:
cout<<"\nEnter the price sold: RM";
cin>>carPrize;
commission=0.02*carPrize;
totalCommission+=commission;
bmwSold++;
system("CLS");
break;
case 3:
cout<<"\nEnter the price sold: RM";
cin>>carPrize;
commission=0.035*carPrize;
totalCommission+=commission;
mbenzSold++;
system("CLS");
break;
default :
cout<<"\nNot available!"<<endl;
system("pause");
return 1;
}
numCar++;
}while(numCar<=carSold);
allMonthlyIncome=allMonthlyIncome+totalCommission+salary;
}
int SalesMan2()
{
char NameTwo[40];
int numCar=1,carSold,carType,audiSold=0,bmwSold=0,mbenzSold=0;
double salary,carPrize,commission,totalCommission,allMonthlyIncome;
cout<<"Name of 2nd Salesman"<<endl;
cin.getline(NameTwo,39);
cout<<"\nMonthly salary: RM";
cin>>salary;
cout<<"\nNumber of car sold in a month: ";
cin>>carSold;
system("CLS");
do{
cout<<"\nEnter type of car sold as below: "<<endl;
cout<<"\n1-Audi"<<endl;
cout<<"2-BMW"<<endl;
cout<<"3-Mercedes Benz"<<endl;
cout<<"\nCar Type:";
cin>>carType;
switch(carType)
{
case 1:
cout<<"\nEnter the price sold: RM";
cin>>carPrize;
commission=0.02*carPrize;
totalCommission+=commission;
audiSold++;
system("CLS");
break;
case 2:
cout<<"\nEnter the price sold: RM";
cin>>carPrize;
commission=0.02*carPrize;
totalCommission+=commission;
bmwSold++;
system("CLS");
break;
case 3:
cout<<"\nEnter the price sold: RM";
cin>>carPrize;
commission=0.035*carPrize;
totalCommission+=commission;
mbenzSold++;
system("CLS");
break;
default :
cout<<"\nNot available!"<<endl;
system("pause");
return 1;
}
numCar++;
}while(numCar<=carSold);
allMonthlyIncome=allMonthlyIncome+totalCommission+salary;
}
In the SalesmanN() functions, end it with:
return totalCommission;
In main(), do:
int allCommissions = 0;
and then in your loop you do:
case 1: allCommissions += SalesMan1(); cycle++; break;
You can CIN into any character array but it is not preferred for names as CIN limits its input on spaces. The SalesmanName will not have any spaces.
char arr[1000];
cin`>>arr;
If you enter "XYZ ABC" as name, then arr[] will store only "XYZ" while "ABC" will remain in the input stream.
For this question you can create a Salesman Class which will encapsulate all the functions nd data required for each Salesman . As the company has only 6 workers you can make a array of 6 object of Salesman Class. So that you can refer to particular salesman's commission as SalesMan[i].getCommission(). Moreover class will help to expand to more number of workers later.

Loop in a switch case statement

I need help with validating a switch case statement i need it to check what the user has entered and if it does not match reject it and tell them to do it again. the one i have at the moment partially works but will reject the first number then break when trying to enter another number. Help If you need to see the whole program just ask.
#include "stdafx.h"
#include "cstdlib"
#include "iostream"
#include "windows.h"
#include "cmath"
using namespace std;
int main(int argc, char* argv[])
{
float ALT0();
float ALT5000();
float ALT10000();
float ALT15000();
float ALT20000();
float ALT25000();
float ALT30000();
float ALT35000();
float ALT40000();
void an_answer(float a);
char Restart;
char op;
float answer;
do
{
cout << "\n\t\t\tOperational Flight Plan\n" << endl;
cout << "For the saftey of everyone on board, there will be 100 kg added to the overall\namount to give the aircraft more fuel incase of a head on wind or delays at the landing airport.\n" << endl;
cout << "Select Altitude the aircraft will fly at: " << endl;
cout << "0 for 0ft\n1 for 5000ft\n2 for 10000ft\n3 for 15000ft\n4 for 20000ft\n5 for 25000ft\n6 for 30000ft\n7 for 35000ft\n8 for 40000ft" << endl;
cin >> op;
switch (op)
{
case'0':
answer=ALT0();
break;
case '1':
answer=ALT5000();
break;
case '2':
answer=ALT10000();
break;
case '3':
answer=ALT15000();
break;
case '4':
answer=ALT20000();
break;
case '5':
answer=ALT25000();
break;
case '6':
answer=ALT30000();
break;
case '7':
answer=ALT35000();
break;
case '8':
answer=ALT40000();
break;
default:
cout << "You must enter a number from 0-8" << endl;
cin >> op;
break;
}
an_answer(answer);
cout << "Do you want to do another calculation? Press Y for yes and anything else to quit.";
cin >> Restart;
} while (Restart=='y' || Restart=='Y');
//system("PAUSE");
//return EXIT_SUCCESS;
}
I'm betting you're hitting enter after entering the number. Your first cin >> op reads the number, but your second one reads the enter key. If you want to read in an entire line, use a function that reads in an entire line.
Alternately, move the second cin >> op up to before the switch statement. This will break if someone enters more than one character before hitting enter but will work otherwise.