I have the following code in which I'm trying to validate the radius. If the radius is zero or negative, I'm supposed to give the user endless opportunities to write the radius again until it's valid. When I tested the code, I wrote a negative value and it worked just fine, it gave me endless opportunities until I gave a valid value, but if I wrote a correct value since the beginning, it made me write the value again as if it was incorrect.
#include <iostream>
#include <stdlib.h>
#include "listaEnlazada.h"
using namespace std;
using namespace listaenlazada;
void menu()
{
cout << "\n\t\tLISTA ENLAZADA SIMPLE\n\n";
cout << "1. Insert at begginig " << endl;
cout << "2. Insert at the end " << endl;
cout << "3. Insert in a specific position " << endl;
cout << "4. Write list " << endl;
cout << "5. Search element " << endl;
cout << "6. Exit " << endl;
}
int main() {
CircPtr cabezaLista = NULL, position;
int op;
string name;
double radius;
double x;
double y;
int pos;
do {
menu();
cin >> op;
switch(op)
{
case 1:
cout << "Write the name of the circle: ";
cin >> name;
cout << "\n Write radius: ";
cin >> radius;
do{
cout << "Invalid input. ";
cin >> radius;
}while(radius <= 0);
cout << "\n Write center: ";
cout << "X: ";
cin >> x;
cout << "Y: ";
cin >> y;
insertarCabeza(cabezaLista, name, radius, x, y);
break;
case 2:
cout << "Write the name of the circle: ";
cin >> name;
cout << "\n Write radius: ";
cin >> radius;
do{
cout << "Invalid input. ";
cin >> radius;
}while(radius <= 0);
cout << "\n Write center: ";
cout << "X: ";
cin >> x;
cout << "Y: ";
cin >> y;
insertarFinal(cabezaLista, name, radius, x, y);
break;
case 3:
cout << "Write the name of the circle: ";
cin >> name;
cout << "\n Write radius: ";
cin >> radius;
do{
cout << "Invalid input. ";
cin >> radius;
}while (radius <= 0);
cout << "\n Write center: ";
cout << "X: ";
cin >> x;
cout << "Y: ";
cin >> y;
cout << "Position : ";
cin >> pos;
posicion = buscarPosicion(cabezaLista, pos-1);
if (posicion != NULL)
insertarPosicion(posicion, name, radius, x, y);
break;
case 4:
cout << "\n\n Showing list : ";
escribirLista(cabezaLista);
break;
case 5:
cout << "\n Center of circle to search: ";
cout << "X: ";
cin >> x;
cout << "Y: ";
cin >> y;
buscarElemento(cabezaLista, x, y);
break;
case 6:
cout << "\n End of the program. ";
break;
}
cout << endl;
}while(op != 6);
return 0;
}
Just use while loop instead of do while loop. In your code because of cin you are taking one input value and for any value which user enters, next do while loop execute ones without checking condition so your prompting with invalid input on the correct radius input.
Instead of this
cout << "\n Write radius: ";
cin >> radius;
do{
cout << "Invalid input. ";
cin >> radius;
}while(radius <= 0);
Do like this
cout << "\n Write radius: ";
cin >> radius;
while(radius <= 0){
cout << "Invalid input. ";
cin >> radius;
}
Learn the basics of the loops.
Related
I am new to c++ and my textbook is not very helpful. I have a few errors in my code. Where I am being told the identifier for customerAccount is undefined, and I have an incompatible declaration with my int search before and after my main. I will post some code below as I have been trying to figure this out for a while and I am at a loss.
#include<iostream>
#include<string>
using namespace std;
struct {
string Name;
string Address;
string City_State_Zip;
double phoneNumber;
double actBalance;
string Payment;
};
//This is where the errors start, saying customer account is undefined
void Display(customerAccount ca);
//declaration is incompatible with int search
int Search(customerAccount, string);
int main() {
customerAccount customers[10];
string SName;
int choice, i = 0, size = 0;
do {
cout << "****Menu****" << endl;
cout << "1. Enter Customer Information" << endl;
cout << "2. Change Customer Information" << endl;
cout << "3. Search For Customer" << endl;
cout << "4. Display Customer Data" << endl;
cout << "5. Exit" << endl;
cout << "Please enter a choice 1,2,3,4 or 5";
cin >> choice;
switch (choice) {
case 1:
cout << "Enter customer name: ";
cin >> customers[i].Name;
cout << "Enter customer address: ";
cin >> customers[i].Address;
cout << "Enter city state and zip: ";
cin >> customers[i].City_State_Zip;
cout << "Enter phone number: ";
cin >> customers[i].phoneNumber;
cout << "Enter account balance: ";
cin >> customers[i].actBalance;
if (customers[i].actBalance < 0) {
cout << "Account balance cannot be negative. Please re-enter: "
<< endl;
cin >> customers[i].actBalance;
}
cout << "Enter last payment: ";
cin >> customers[i].Payment;
i++;
break;
case 2: int ele;
cout << "Enter customer information to modify: " << endl;
cout << "Enter customer name: ";
cin >> customers[ele - 1].Name;
cout << "Enter customer address: ";
cin >> customers[ele - 1].Address;
cout << "Enter city state and zip";
cin >> customers[ele - 1].City_State_Zip;
cout << "Enter phone number: ";
cin >> customers[ele - 1].phoneNumber;
cout << "Enter account balance: ";
cin >> customers[ele - 1].actBalance;
if (customers[ele - 1].actBalance < 0) {
cout << "Account balance cannot be negative. Please re-enter: "
<< endl;
cin >> customers[i].actBalance;
}
cout << "Enter date of payment: ";
cin >> customers[ele - 1].Payment;
break;
case 3: cout << "Enter customer name to search: ";
cin >> SName;
for (size = 0; size < i; size++) {
int check;
check = Search (customers[size], SName);
if (check == 1)
Display(customers[size]);
}
break;
case 4:
for (size = 0; size < i; size++)
Display(customers[size]);
break;
case 5: exit(0);
break;
}
} while (choice != 5);
system("pause");
return 0;
}
void Display(customerAccount ca) {
cout << " Customer name:";
cout << ca.Name << endl;
cout << " Address:";
cout << ca.Address << endl;
cout << " city state and zip:";
cout << ca.City_State_Zip << endl;
cout << " Phone number:";
cout << ca.phoneNumber << endl;
cout << " Account balance:";
cout << ca.actBalance << endl;
cout << " Date of payment:";
cout << ca.Payment << endl;
}
//declaration is incompatible with int search
int Search(customerAccount ca, string str) {
if (str.compare(ca.Name) == 0)
return 1;
else
return 0;
}
case 2: int ele;
On this line you have an uninitialized variable which is causing your bug.
So I am not really sure what to do here, I have gone back over my code multiple times and it all seems to be right but I keep getting the error code
Stubblefield9.cpp:74: undefined reference to `distance(float, float, float, float)'
collect2.exe: error: ld returned 1 exit status
Here is my code if anyone can help me.
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main()
{
const float pi=3.14;
int choice;
char again;
do
{
cout << " IHCC Computer Science Registration Menu\n";
cout << " ======================================\n";
cout << " 1. The Volume of a Cone\n";
cout << " 2. The Volume of a Sphere\n";
cout << " 3. The Area of an Octagon\n";
cout << " 4. The Destance between two Points\n";
cout << " ======================================\n";
cout << " Enter your selection: ";
cin >> choice;
switch (choice)
{
case 1:
float coneRadius,coneHeight,coneVolume;
cout<<"Enter the Radius of the cone:";
cin>>coneRadius;
cout<<"\nEnther the Height of the Cone: ";
cin>>coneHeight;
coneVolume=pi*coneRadius*coneRadius*coneHeight/3;
cout<<"\nThe Volume of a Cone with Radius ("<< coneRadius << ") and Height (" << coneHeight << setprecision(2) << fixed << ") is " << coneVolume;
break;
case 2:
float sphereRadius,sphereVolume;
cout << "Please insert the Radius: ";
cin >>sphereRadius;
sphereVolume = (4/3)*(pi)*(sphereRadius*sphereRadius*sphereRadius);
cout<<"Volume with radius "<< setprecision(1) << fixed << sphereRadius << setprecision(2) << fixed << " is "<<sphereVolume;
break;
case 3:
float octagonSide, octagonArea;
cout << "Input side length: ";
cin >> octagonSide;
octagonArea =(2 * (1 + sqrt(2)) * octagonSide * octagonSide);
cout << "\nThe area of the octagon with side length (" << octagonSide << setprecision(2) << fixed << ") is "<< octagonArea;
break;
case 4:
float x, y, a, b, answer;
float distance(float x, float y, float a, float b);
cout << "Enter the points for the coordinates";
cout << endl;
cout << "Point x for first coordinates: ";
cin >> x;
cout << endl;
cout << endl;
cout << "Point y for first coordinate: ";
cin >> y;
cout << endl;
cout << endl;
cout << "Point x for the second coordinate: ";
cin >> a;
cout << endl;
cout << endl;
cout << "Point y for the second coordinate: ";
cin >> b;
cout << endl;
cout << endl;
answer = distance(x, y, a, b);
cout << "The answer is " << answer;
break;
default:
cout << "Not a Valid Choice. \n";
cout << "Choose again.\n";
cin >> choice;
break ;
}
cout << "\n\n Would you like to do it again(y or n)";
cin >> again;
} while( again == 'y' || again == 'Y' );
return 0;
}
You get that error because you try to call a function distance() that is declared in your code by
float distance(float x, float y, float a, float b);
but not defined.
The problem I am having is that I do not know how to read a specific number out of a text file that was created and had values entered into it earlier in the program.
I was hoping to use a nested loop statement for reading in the values after the values of the quizes are read in I need to add up the values and average them out and this needs to happen multiple times
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
using namespace std;
int main()
{
string StudentGrades;
int studentID;
double quiz1;
double quiz2;
double quiz3;
double quiz4;
double total=0;
double choice;
ofstream outFile;
cout << "Enter student ID number, Quiz 1 Grade, Quiz 2 Grade , Quiz 3 Grade, Quiz 4 Grade" << endl;
outFile.open("StudentGrades.txt");
//while (outFile.open)
//{
for (int x = 0; x < 4; x++)
{
cout << "Enter student ID: ";
cin >> studentID;
cout << "Enter quiz grade 1: ";
cin >> quiz1;
//cout << quiz1;
cout << "Enter quiz grade 2: ";
cin >> quiz2;
//cout << quiz2;
cout << "Enter quiz grade 3: ";
cin >> quiz3;
//cout << quiz3;
cout << "Enter quiz grade 4: ";
cin >> quiz4;
//cout << quiz4;
cout << endl;
//outFile.open("StudentGrades.txt");
if (outFile.is_open())
{
cout << "inside if/else outFile" << endl;
//outFile << "File successfully open";
outFile << studentID << " " << quiz1 << " " << quiz2 << " " << quiz3 << " " << quiz4 << endl;
}
else
{
cout << "Error opening file";
}
cout << "Enter 0 for no more students. Enter 1 for more students." << endl;
cin >> choice;
if (choice == 1)
continue;
if (choice == 0)
{
outFile.close();
break;
}
}
//}
//declaring file and opening it
ifstream inFile;
inFile.open("StudentGrades.txt");
while (inFile>>studentID)
{
cout << studentID<< quiz1 <<quiz2<<quiz3<<quiz4<< endl;
}
system("pause");
return (0);
}
You are not reading all the fields from the input file, you are reading just the studentID.
while (inFile>>studentID)
{
cout << studentID<< quiz1 <<quiz2<<quiz3<<quiz4<< endl;
}
Try:
while (inFile >> studentID >> quiz1 >> quiz2 >> quiz3 >> quiz4)
{
cout << studentID << quiz1 << quiz2 << quiz3 << quiz4 << endl;
}
Update
Below is my suggestion for a refactored program. It's good to create functions that perform specific tasks and then call them from a higher level function instead of jamming them all in one large function.
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
using namespace std;
void saveStudentData(string const& filename)
{
int studentID;
double quiz1;
double quiz2;
double quiz3;
double quiz4;
// Use int type for choice, not double
int choice;
ofstream outFile(filename);
if (!outFile.is_open())
{
// Problem opening file.
cout << "Error opening file";
return;
}
cout << "Enter student ID number, Quiz 1 Grade, Quiz 2 Grade , Quiz 3 Grade, Quiz 4 Grade" << endl;
for (int x = 0; x < 4; x++)
{
cout << "Enter student ID: ";
cin >> studentID;
cout << "Enter quiz grade 1: ";
cin >> quiz1;
cout << "Enter quiz grade 2: ";
cin >> quiz2;
cout << "Enter quiz grade 3: ";
cin >> quiz3;
cout << "Enter quiz grade 4: ";
cin >> quiz4;
cout << endl;
outFile << studentID << " " << quiz1 << " " << quiz2 << " " << quiz3 << " " << quiz4 << endl;
cout << "Enter 0 for no more students. Enter 1 for more students." << endl;
cin >> choice;
if (choice == 0)
{
break;
}
}
}
void readStudentData(string const& filename)
{
int studentID;
double quiz1;
double quiz2;
double quiz3;
double quiz4;
double total=0;
ifstream inFile(filename);
while (inFile >> studentID >> quiz1 >> quiz2 >> quiz3 >> quiz4)
{
total = (quiz1 + quiz2 + quiz3 + quiz4);
cout << studentID << " " << quiz1 << " " << quiz2
<< " " << quiz3 << " " << quiz4 << " " << total << endl;
}
}
int main()
{
string filename("StudentGrades.txt");
saveStudentData(filename);
readStudentData(filename);
return (0);
}
I have this code where in option lists will display when run. my problem is when I enter number 2, the option 2 program doesn't work well. It just go directly to asking the amount paid instead of asking first the cost of purchase.
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
float circle (float a)
{
float z;
z = 3.141593 * (a * a);
return (z);
}
float square (float b)
{
float y;
y = b * b;
return (y);
}
float rectangle (float c, float d)
{
float x;
x = c * d;
return (x);
}
float triangle (float e, float f)
{
float w;
w = (e * f) / 2;
return (w);
}
void exit ()
{
cout << "THANK YOU! GOODBYE!" << endl;
}
int main()
{
int x;
do
{
cout << "Please choose an option below: \n";
cout << "1. Area of Shapes\n";
cout << "2. Cost of your items\n";
cout << "3. Flood Control\n";
cout << "4. Fibonacci Numbers\n";
cout << "5. Addition Table\n";
cout << "6. Exit\n";
cin >> x;
if (x == 1)
{
system("cls");
float n;
float l;
float m;
float radius;
float side;
float length;
float width;
float base;
float height;
do
{
cout << "1 => Area of Circle" << endl;
cout << "2 => Area of Square" << endl;
cout << "3 => Area of Rectangle" << endl;
cout << "4 => Area of Trian1gle" << endl;
cout << "5 => Return to Main Menu" << endl;
cout << "0 => Exit" << endl;
cout << "Please enter number of your choice: ";
cin >> n;
system("cls");
{
if (n == 0)
{
exit ();
system("pause");
return 0;
}
else if (n == 1)
{
cout << "Enter radius of the circle: ";
cin >> radius;
l = circle (radius);
cout << "Area of the circle is: " << l << endl;
system("pause");
system("cls");
}
else if (n == 2)
{
cout << "Enter side of the square: ";
cin >> side;
cout << "Area of the square is: " << square (side) << endl;
system("pause");
system("cls");
}
else if (n == 3)
{
cout << "Enter length of the rectangle: ";
cin >> length;
cout << "Enter width of the rectangle: ";
cin >> width;
m = rectangle (length, width);
cout << "Area of the rectangle is: " << m << endl;
system("pause");
system("cls");
}
else if (n == 4)
{
cout << "Enter base of the triangle: ";
cin >> base;
cout << "Enter height of the triangle: ";
cin >> height;
cout << "Area of the triangle is: " << triangle (base, height) << endl;
system("pause");
system("cls");
}
else if (n == 5)
{
exit ();
}
else
cout << "Invalid number. Please enter a valid number below" << endl;
}
}
while (n != 0 && n != 5);
cout << endl << endl;
system("pause");
system("cls");
}
else if (x == 2)
{
system("cls");
string mystr;
float cost = 0;
float amount = 0;
float total;
cout << "Total Cost: P";
getline (cin, mystr);
stringstream(mystr) >> cost;
cout << endl;
total = cost * .06;
cout << "Sales Tax Value: P" << total << endl;
cout << endl;
cout << "Cost of Item: P" << cost + total << endl;
cout << endl;
cout << "Amount Paid: P";
getline (cin, mystr);
stringstream(mystr) >> amount;
cout << endl;
cout << "Total Amount Purchased: P" << cost << endl;
cout << "Sales Tax Value: P" << total << endl;
cout << "Total Amount + Sales Tax: P" << cost + total << endl;
cout << "Total Amount Paid: P" << amount << endl;
cout << "Change: P" << amount - (cost + total) << endl;
system("pause");
cout << endl;
cout << "THANK YOU! ENJOY YOUR MEAL!" << endl;
system("pause");
system("cls");
}
else if (x > 6)
cout << "Invalid Input";
else
{
system("pause");
return 0;
}
}
while (x != 6);
system("pause");
return 0;
}
EDIT
For the posters education
You do
switch (n) {
case 1:
//... Code for n == 1 - If long put into another function. If using local variables put code bloc in braces
break;
case 2:
// Diitto for n==2
default: // No match
// All other values of n not listed above
}
What went wrong
Say you type your menu selection:
2<Enter>
Then the content of the std::cin stream will be:
2\n
When your menu selection runs...
cin >> x;
...it reads a number off the line but doesn't consume any trailing whitespace nor the newline, so the remaining state content could be denoted like this:
\n
Then your code for menu option 2 starts running:
cout << "Total Cost: P";
getline (cin, mystr);
...the getline looks at std::cin and finds the left over \n mentioned above, and says "hey, an empty line - I'll set mystr to an empty string". Notice that it did not do what you'd hoped: namely wait for you to type some more input and read that into mystr.
How to fix it
Before calling getline(cin, mystr) you want to remove the left-over \n typed when entering the menu selection. The code changes for that (adding error handling too):
#include <limits>
...
cout << "Total Cost: P";
std::cin.ignore(std::numeric_limits<streamsize>::max(), '\n');
if (!std::getline(std::cin, mystr))
{
std::cerr << "unable to read mystr\n";
exit(1);
}
std::istringstream iss(mystr);
iss >> cost;
if (!iss)
{
std::cerr << "mystr doesn't contain a valid cost number\n";
exit(1);
}
How you could have found the problem
When you get stuck like this, try adding some "trace" statements to print out the values of variables and find where they differ from your expectation... that can at least give you a better idea how to isolate and describe the problem, and what to google for to fix it.
std::out << "mystr '" << mystr << "'\n";`
Try to use error handling like I've illustrated so the program stops (or prompts for better input) when there's a problem parsing the user's input.
I have an error with my switch statement in this baseball calculator. The error says :" transfer of control bypasses initialization of:"
The switch statement is used for the types of calculations you want to do in this program like:
On base percentage
Batting Average
etc...
// Baseball Stat.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
char menu_choice;
// Batting average formula.
float b_average(float hits, float bats) {return hits/bats;};
// On base percentage formula
float OBP(float hits, float walks, float Hit_by_Pitch, float bats, float sac_flys) {return (hits+walks+Hit_by_Pitch) / (bats+walks+Hit_by_Pitch+sac_flys);};
// Strikeout Ratio Formula
float Strikeout_ratio(float strikeouts, float bats) {return strikeouts/bats;};
// Fielding Average Formula
float fielding_average(float putouts, float assists, float errors) {return (putouts+assists) / (putouts + assists+errors);};
// Range Factor Formula
float range_factor(float putouts , float assists, float defins) {return (putouts+assists) * 9 / defins;};
// Pythagorean Expectation Formula
float pyt_expectation(double runs, double runs_allowed) {return (pow(runs, 1.83) / (pow(runs, 1.83) + pow(runs_allowed, 1.83))) * 100;};
int _tmain(int argc, _TCHAR* argv[])
{
cout << "BASEBALL STATISTICS CALCULATOR\n";
cout << "\nWhat do you want to calculate?\n""\nA.BATTING AVERAGE\n""\nB.ON BASE PERCENTAGE (OBP)\n""\nC.STRIKEOUT RATIO\n""\nD.FIELDING AVERAGE\n""\nE.RANGE FACTOR\n""\nF.BASEBALL GAME SIMULATOR\n";
cin >> menu_choice;
here's the error:
switch(menu_choice)
{
case 'A':
// Variables for First Player's Batting Average.
int atBatsBA;
int numHitsBA;
// Variables for Second Player's Batting Average.
int second_atBatsBA;
int second_numHitsBA;
cout << "\nBATTING AVG\n\n";
cout << "Player #1 At bats:\n";
cin >> atBatsBA;
cout << "Player #1 Hits:\n";
cin >> numHitsBA;
cout << "Player #2 At Bats:\n";
cin >> second_atBatsBA;
cout << "Player #2 Hits:\n";
cin >> second_numHitsBA;
cout << "\nPlayer #1's Batting Average is:\n" << b_average(numHitsBA, atBatsBA) << endl;
cout << "\nPlayer #2's Batting Average is:\n" << b_average(second_numHitsBA, second_atBatsBA) << endl;
break;
case 'B':
// Variables for First Player's OBP
int atBatsOBP;
int hitsOBP;
int walksOBP;
int Hit_By_PitchOBP;
int sa_flysOBP;
// Variables for Second Player's OBP
int second_atBatsOBP;
int second_hitsOBP;
int second_walksOBP;
int second_Hit_By_PitchOBP;
int second_sa_flysOBP;
cout << "\nOBP PERCENTAGE\n";
cout << "\nPlayer #1 At bats:\n";
cin >> atBatsOBP;
cout << "Player #1 Hits:\n";
cin >> hitsOBP;
cout << "Player #1 Walks:\n";
cin >> walksOBP;
cout << "Player #1 Hits by Pitch:\n";
cin >> Hit_By_PitchOBP;
cout << "Player #1 Sac Flys:\n";
cin >> sa_flysOBP;
cout << "Player #2 At bats:\n";
cin >> second_atBatsOBP;
cout << "Player #2 Hits:\n";
cin >> second_hitsOBP;
cout << "Player #2 Walks:\n";
cin >> second_walksOBP;
cout << "Player #2 Hits by Pitch:\n";
cin >> second_Hit_By_PitchOBP;
cout << "Player #2 Sac Flys:\n";
cin >> second_sa_flysOBP;
cout << "\nPlayer #1's OBP:\n" << OBP(hitsOBP,walksOBP,Hit_By_PitchOBP,atBatsOBP,sa_flysOBP) << endl;
cout << "\nPlayer #2's OBP:\n" << OBP(second_hitsOBP,second_walksOBP,second_Hit_By_PitchOBP,second_atBatsOBP,second_sa_flysOBP) << endl;
break;
case 'C':
// Variables for First Player's Strikeout Ratio
int atBatsSOR;
int strikeoutsSOR;
// Variables for Second Player's Strikeout Ratio
int second_atBatsSOR;
int second_strikeoutsSOR;
cout << "\nSTRIKEOUT RATION\n";
cout << "\nPlayer #1 At bats:\n";
cin >> atBatsSOR;
cout << "\nPlayer #1 Strikeouts:\n";
cin >> strikeoutsSOR;
cout << "\nPlayer #2 At bats:\n";
cin >> second_atBatsSOR;
cout << "\nPlayer #2 Strikeouts:\n";
cin >> second_strikeoutsSOR;
cout << "\nPlayer #1's Strikeout Ratio:\n" << Strikeout_ratio(strikeoutsSOR,atBatsSOR) << endl;
cout << "\nPlayer #2's Strikeout Ratio:\n" << Strikeout_ratio(second_strikeoutsSOR,second_atBatsSOR) << endl;
break;
case'D':
// Variables for First Player's Fielding Average.
int putoutsFA;
int assistsFA;
int errorsFA;
// Variables for Second Player's Fielding Average.
int second_putoutsFA;
int second_assistsFA;
int second_errorsFA;
cout << "\nFIELDING AVERAGE\n";
cout << "\nPlayer #1's putouts:\n";
cin >> putoutsFA;
cout << "Player #1's assists:\n";
cin >> assistsFA;
cout << "Player #1's errors:\n";
cin >> errorsFA;
cout << "Player #2's putouts:\n";
cin >> second_putoutsFA;
cout << "Player #2's assists:\n";
cin >> second_assistsFA;
cout << "Player #2's errors:\n";
cin >> second_errorsFA;
cout << "\nPlayer #1's Fielding Average:\n" << fielding_average(putoutsFA, assistsFA, errorsFA) << endl;
cout << "\nPlayer #2's Fielding Average:\n" << fielding_average(second_putoutsFA, second_assistsFA, second_errorsFA) << endl;
break;
case 'E':
// Variables for First Player's Range Factor.
int putoutsRF;
int assistsRF;
int defensive_inningsRF;
// Variables for Second Player's Range Factor.
int second_putoutsRF;
int second_assistsRF;
int second_defensive_inningsRF;
cout << "\nRANGE FACTOR\n";
cout << "\nPlayer #1's putouts:\n";
cin >> putoutsRF;
cout << "Player #1's assists:\n";
cin >> assistsRF;
cout << "Player #1's Defensive Innings Played:\n";
cin >> defensive_inningsRF;
cout << "Player #2's putouts:\n";
cin >> second_putoutsRF;
cout << "Player #2's assists:\n";
cin >> second_assistsRF;
cout << "Player #2's Defensive Innings Played:\n";
cin >> second_defensive_inningsRF;
cout << "\nPlayer #1's Range Factor:\n" << range_factor(putoutsRF, assistsRF, defensive_inningsRF) << endl;
cout << "\nPlayer #2's Range Factor:\n" << range_factor(second_putoutsRF, second_assistsRF, second_defensive_inningsRF) << endl;
break;
case'F':
// Variables for first team's batting average.
string ftname;
int atbatsTBA;
int hitsTBA;
// Variables for second team's batting average.
string stname;
int second_atbatsTBA;
int second_hitsTBA;
cout << "\nBASEBALL GAME SIMULATOR\n";
cout << "\nPlease enter the first team's name:\n";
cin >> ftname;
cout << "\nPlease enter the second team's name:\n";
cin >> stname;
cout << "\nPlease enter the first teams' total at bats:\n";
cin >> atbatsTBA;
cout << "\nPlease enter the first teams's total hits:\n";
cin >> hitsTBA;
cout << "\nPlease enter the second team's total at bats:\n";
cin >> second_atbatsTBA;
cout << "\nPlease enter the second team's total hits:\n";
cin >> second_hitsTBA;
cout << "\n" << ftname << " 's Batting Average is:\n" << b_average(atbatsTBA, hitsTBA) << "\n";
cout << "\n" << stname << " 's Batting Average is:\n" << b_average(second_atbatsTBA, second_hitsTBA) << "\n";
int TBA;
int TBA2;
TBA = b_average(atbatsTBA, hitsTBA);
TBA2 = b_average(second_atbatsTBA, second_hitsTBA);
if(TBA>TBA2){
cout << ftname <<" Wins!!\n";
}
else if(TBA<TBA2){
cout << stname << " Wins!!\n";
}
else{
cout << "It's a draw!!\n";
}
break;
default :
cout << "Please enter a valid option\n";
}
return 0;
}
You can't declare variables inside of switch cases unless you add a new scope. Just change each of your cases to look like this instead:
case 'X': {
// original contents
} break;
That will allow you to declare new variables inside the scope delimited by the {}s and avoid this error.