I have an assignment where we need to have 2 parallel arrays one is a list of city names and the other is sales amounts. Here is a copy of the problem:
Program Description:
It needs to compile sales totals for various cities in the USA. Specifically, when the program is run, the user will be prompted to enter a city. If the city is correct, the user will then be prompted to enter a sales amount. If the city doesn’t exist on the list, the user will get an error message (and no sales amount prompt). If a sales amount is entered, it will accumulate into a total for that city. Either way (city exists on the list or not) , the user will then be asked to enter another city or quit.
Once the user quits, the city name and total should be displayed for all cities, one per line. Following that the program should stop.
There are only 8 cities to choose from. 2 parallel arrays must be used, initialized as follows:
City (String) Sales (Integer)
------------- ---------------
Atlanta 0
Buffalo 0
Chicago 0
Dallas 0
Houston 0
Honolulu 0
Miami 0
Reno 0
All input is guaranteed to be single-word followed by enter only. It may not match a city name, but there will be no spaces. This keeps your program simple as it lets you avoid using getline( ), which would be needed to deal with blanks between words.
Sales data is guaranteed good when input.
When I attempted to run my program, visual studios went crazy, and I've pulled out my hair trying to fix it. If someone could help give me some pointers on what I've done wrong, I would greatly appreciate it. Here is a copy of my program:
#include <iostream>
#include <string>
using namespace std;
int main()
{
//declare city and sales array
string city[8] = {" "};
int sales[8] = {0};
//declare variables
string cityName = " ";
int cityTotal = 0;
int salesAmt = 0;
int i = 0;
char another = ' ';
//init city array
city[0] = "Atlanta";
city[1] = "Buffalo";
city[2] = "Chicago";
city[3] = "Dallas";
city[4] = "Houston";
city[5] = "Honololu";
city[6] = "Miami";
city[7] = "Reno";
do
{
//input city name and if found input sales amount
cout << "Enter a City: Atlanta, Buffalo, Chicago, Dallas, Houston, Honololu, Miami, or Reno: ";
cin >> cityName;
for(i = 0; i <= 8; i++)
{
if(cityName == city[i])
{cout << "Enter sales amount: ";
cin >> salesAmt;
salesAmt += sales[i];}
else
{cout << "ERROR: CITY NOT AVAILIABLE" << endl;
cout << endl;}
//end if
}
//end for loop
//ask if another city
cout << "Enter another city?: ";
cin >> another;
} //end do loop
while(another == 'Y' || another == 'y');
{
for(i = 0; i <= 8; i++)
{
cout << "City: " << " " << "Sales: " << endl;
cout << city[i] << " " << sales[i] << endl;
}
//end for loop
} //end while loop
system("pause");
return 0;
} //end of main
A clear error here is the way you have used the index to access the arrays, you can't have the for loop reach 8, as the array's index is only up to 7. change your for loops to:
for(i = 0; i < 8; i++)
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
int main()
{
//declare city and sales array
string city[8] = {" "};
int sales[8] = {0};
//declare variables
string cityName ="";
int cityTotal = 0;
int salesAmt = 0;
int i = 0;
char another = ' ';
//init city array
city[0] = "Atlanta";
city[1] = "Buffalo";
city[2] = "Chicago";
city[3] = "Dallas";
city[4] = "Houston";
city[5] = "Honololu";
city[6] = "Miami";
city[7] = "Reno";
do
{
//input city name and if found input sales amount
cout << "Enter a City: Atlanta, Buffalo, Chicago, Dallas, Houston, Honololu, Miami, or Reno: ";
cin >> cityName;
for(i = 0; i < 8; i++)
{
if(cityName == city[i])
{
cout << "Enter sales amount: ";
cin >> salesAmt;
sales[i] += salesAmt;
} else if (i==7)
{
cout << "ERROR: CITY NOT AVAILIABLE" << endl;
}//end if
}//end for loop
//ask if another city
cout << "Enter another city?: ";
cin >> another;
} //end do loop
while(another == 'Y' || another == 'y');
{
for(i = 0; i < 8; i++)
{
cout << "City: " << " " << "Sales: " << endl;
cout << city[i] << " " << sales[i] << endl;
}
//end for loop
} //end while loop
system("pause");
return 0;
} //end of main
error was for(i = 0; i <= 8; i++) change with for(i = 0; i < 8; i++) and also second for.
Next error changed to sales[i] += salesAmt; and Not salesAmt +=sales[i];.
And your city name is case sensitive when you input city name!
Related
This program will need to handle all grades for 10 students.
Each student has a first and last name, an id number,
3 homework grades, 3 labs grades, 3 test grades, and 1 final exam grade.
display the final course grade in both numbered and letter version
The equation only works for the first set of grades then it adds a little bit to the next average I just can't figure out whats wrong.
/*This program will need to handle all grades for 10 students.
Each student has a first and last name, an id number,
3 homework grades, 3 labs grades, 3 test grades, and 1 final exam grade.
display the final course grade in both numbered and letter version
*/
#include <iostream> // main library
#include <string> //enables use of strings
#include <iomanip> // for setw
#include <Windows.h> // used to set console title
using namespace std; // for cout and cin
const int MAXSTUDENTS = 2;
const int MAXGRADES = 3;
const int MINGRADES = 1;
int main()
{// Get names form students
SetConsoleTitle("Gradebook");
double hwGrade[MAXSTUDENTS][MAXGRADES];
double labGrade[MAXSTUDENTS][MAXGRADES];
double testGrade[MAXSTUDENTS][MAXGRADES];
double feGrade[MAXSTUDENTS];
double final_num_grade[MAXSTUDENTS];
double hwAve =0, labAve=0, testAve=0; // this will be used to calculate the averages
string fName[MAXSTUDENTS];
string lName[MAXSTUDENTS];
string line; // to set the two string variables
string id[MAXSTUDENTS]; // id will be a whole number so int was apropiate
//first for statement. ensuere that the program is run 10 times
for (int s = 0; s < MAXSTUDENTS; s++) {
cout << "Enter student's first name: "; // ask the user for the first name
getline(cin, fName[s]); // accepts students first name
cout << "Enter stedent's last name: "; //ask the user for last name
getline(cin, lName[s]); // accepts students last name
cout << "Enter student's id: "; // ask user for student id
getline(cin, id[s]);
// this loop will ask for three homework grades
for (int n = 0; n < MAXGRADES; n++) {
cout << "Homework grade " << n + 1 << " is "; //tells the user waht the program needs
cin >> hwGrade[s][n]; //lets the user input the homework grades
hwAve += hwGrade[s][n];
}
hwAve = hwAve / 3;
// this loop will ask for three lab grades
for (int l = 0; l < MAXGRADES; l++) {
cout << "Lab grade " << l + 1 << " is ";
cin >> labGrade[s][l]; //lets the user input the LAB grades
labAve += labGrade[s][l];
}
labAve = labAve / 3;
//this loop will ask for three test grades
for (int t = 0; t < MAXGRADES; t++) {
cout << "Test grade " << t + 1 << " is ";
cin >> testGrade[s][t]; //lets the user input the test grades
testAve += testGrade[s][t]; // the average is calculated
}
testAve = testAve / 3;
cout << "Final exam grade: "; // asks user for final exam grade
cin >> feGrade[s];
// equation to get the final course grade
final_num_grade[s] = (hwAve * 0.20) + (labAve * 0.25) + (testAve * 0.30) + (feGrade[s] * 0.25);
line.assign(50, '-');
cout << line << endl;
}
for (int i = 0; i < MAXSTUDENTS; i++) {
cout << "Final Course Grade for " << fName[i] << " " << lName[i] << " with the id " << id[i] << " is " // displays name of student
<< showpoint << fixed << setprecision(1) << final_num_grade[i]; //set to 1 decimal place
//if statement shows the letter grade
if (final_num_grade[i] >= 89.5) { //A if student made 89.5 or more
cout << " (A)\n";
}
else if (final_num_grade[i] >= 79.5) { //B if student made 79.5 to 89.4
cout << " (B)\n";
}
else if (final_num_grade[i] >= 69.5) { // C if student made 69.5 yo 79.4
cout << " (C)\n";
}
else if (final_num_grade[i] >= 59.5) { // D if student made 59.5 to 69.4
cout << " (D)\n";
}
else { // F if student made less than 59.4
cout << " (F)\n";
}
}
return 0;
}
You haven't reset these variables to zero : hwAve, labAve, testAve which makes the second student's grade will be slightly higher
How to fix the code? I can't use vectors. I need to be able to call the names for the courses from the first while to the second one and display them.
cout << "Please enter the number of classes"<< endl;//Number of classes for the while
cin >> nclass;
while (count <= nclass ) // while
{
//Information for the class
{
cout << "Please enter the course name for the class # "<< count << endl;
getline (cin, name);
string name;
string coursename[nclass];
for (int i = 0; i < nclass; i++) {
coursename[i] = name;
}
}
char choose;
cin >> choose;
while ( choose == 'B' || choose == 'b') {//Name the courses
for (int x = 0; x < nclass; x++){
cout << "Here is a list of all the courses: \n" << coursename[i] << endl;
}
return 0 ;
}
you are declaring coursename as local inside loop and then using it outside so you get a compile time error (coursename is undeclared identifier).
one question: what is the role of inner for-loop????!!!
you use a for loop inside while loop through which you are assigning all the elements the same value as the string name has!!!
so every time count increments the inner for loop assigns the new value of name after being assigned, to the all elements of coursename.
count is undefined! so declare it and initialize it to 1 or 0 and take this in mind.
you wrote to the outbounds of coursname: count <= nclss to correct it:
while(count < nclass)...
another important thing: clear the input buffer to make cin ready for the next input. with cin.ignore or sin.sync
cout << "Please enter the number of classes"<< endl;//Number of classes for the while
cin >> nclass;
string coursename[nclass];
int count = 0;
while (count < nclass ) // while
{
//Information for the class
string name;
cout << "Please enter the course name for the class # "<< count << endl;
cin.ignore(1, '\n');
getline (cin, name);
coursename[count] = name;
cin.ignore(1, '\n');
count++;
}
char choose;
cin >> choose;
while ( choose == 'B' || choose == 'b') {//Name the courses
for (int x = 0; x < nclass; x++){
cout << "Here is a list of all the courses: \n" << coursename[x] << endl;
}
This code works!
#include <iostream>
#include <string>
using namespace std;
int main()
{
int nclass = 0, count = 1, countn = 1;
string name[100];
cout << "Please enter the number of classes" << endl;
cin >> nclass;
while (count <= nclass) {
cout << "Please enter the course name for the class # " << count << endl;
cin >> name[count];
count++;
}
cout << "Here is a list of all the courses: " << endl;
while (countn <= nclass) {
cout << name[countn] << endl;
countn++;
}
return 0;
}
Note that gave the array "name" the size of 100. Nobody is going to have 100 classes! There is no need for the for loops. It is a good practice to initialize the count and the new count which is designated by countn. Why is my answer voted down when it works?
I am working on a grade book project that has 5 students that I want to read the names in for and then with an inner loop grab 4 grades for each student. Something is not working on this loop. This what I am getting:
Please enter the name for student 1: Dave
Please enter the grade number 1 for Dave: 100
Please enter the grade number 2 for Dave: 100
Please enter the grade number 3 for Dave: 100
Please enter the grade number 4 for Dave: 10
Please enter the name for student 2: James
Please enter the grade number 5 for James: 100
Please enter the name for student 3: Sam
Please enter the grade number 5 for Sam: 100
Please enter the name for student 4: Jack
Please enter the grade number 5 for Jack: 100
Please enter the name for student 5: Mike
Please enter the grade number 5 for Mike: 100
It should grab 4 grades before it jumps to the next student. I have not been able to figure this out for the last couple hours. Here is the code I have so far:
#include <iostream>
#include <string>
using namespace std;
const int STUDENTS = 5; //holds how many students we have
const int SCORES = 4;
void getNames(string names[], double student1[SCORES], double student2[SCORES],
double student3[SCORES], double student4[SCORES], double student5[SCORES], int SCORES, int STUDENTS);
int main()
{
string names[STUDENTS] = {""};
char grades[STUDENTS] = {""};
double student1[SCORES] = {0};
double student2[SCORES] = {0};
double student3[SCORES] = {0};
double student4[SCORES] = {0};
double student5[SCORES] = {0};
getNames(names, student1, student2, student3, student4, student5, SCORES, STUDENTS);
// Make sure we place the end message on a new line
cout << endl;
// The following is system dependent. It will only work on Windows
system("PAUSE");
return 0;
}
void getNames(string names[], double student1[SCORES], double student2[SCORES],
double student3[SCORES], double student4[SCORES], double student5[SCORES], int SCORES, int STUDENTS)
{
for (int i = 0; i < STUDENTS; i++)
{
cout << "Please enter the name for student " << i+1 << ": ";
cin >> names[i];
cout << endl;
if (i == 0)
{
int count1 = 0;
for (count1; count1 < SCORES; count1++)
{
cout << "Please enter the grade number " << count1+1 << " for " << names[i] <<": ";
cin >> student1[count1];
cout << endl;
}
}
else if (i == 1)
{
int count2 = 0;
for (count2; count2 < SCORES; count2++);
{
cout << "Please enter the grade number " << count2+1 << " for " << names[i] <<": ";
cin >> student2[count2];
cout << endl;
}
}
else if (i == 2)
{
int count3 = 0;
for (count3; count3 < SCORES; count3++);
{
cout << "Please enter the grade number " << count3+1 << " for " << names[i] <<": ";
cin >> student3[count3];
cout << endl;
}
}
else if (i == 3)
{
int count4 = 0;
for (count4; count4 < SCORES; count4++);
{
cout << "Please enter the grade number " << count4+1 << " for " << names[i] <<": ";
cin >> student4[count4];
cout << endl;
}
}
else
{
int count5 = 0;
for (count5; count5 < SCORES; count5++);
{
cout << "Please enter the grade number " << count5+1 << " for " << names[i] <<": ";
cin >> student5[count5];
cout << endl;
}
}
}
}
Thanks for any help on this!
There's some pretty rough stuff going on in here, but the problem is that you have a semi-colon on all your inner loops except the first one:
for (count2; count2 < SCORES; count2++);
Remove the semi-colon, and the stuff in the braces will become part of the loop.
I'm going to suggest you make your code a little tidier and less error-prone by chucking all those function arguments into their own array when you enter the function, like this:
double *scores[5] = { student1, student2, student3, student4, student5 };
Then you take OUT all that repetition - the copy/paste is what caused your problems to begin with:
for (int i = 0; i < STUDENTS; i++)
{
cout << "Please enter the name for student " << i+1 << ": ";
cin >> names[i];
cout << endl;
for (int s = 0; s < SCORES; s++)
{
cout << "Please enter the grade number " << s+1 << " for " << names[i] <<": ";
cin >> scores[i][s];
cout << endl;
}
}
Why can't you use two nested loops like
for (int studix=0, stduix<STUDENTS; studix++) {
//...
for (int gradix=0; gradix<SCORE; gradix++) {
//...
}
//....
}
BTW, the condition could be a more complex one, e.g. with the internal loop being
bool goodgrade=true;
for (int gradix=0; goodgrade && gradix<SCORE; gradix++) {
// you could modify goodgrade or use break; inside the loop
}
Don't forget the possible use of continue and break inside a loop.
And please, take time to read some good C++ programming book
Building on Basile's answer and my comments:
int main()
{
string names[STUDENTS] = {""};
char grades[STUDENTS] = {""};
double student1[SCORES] = {0};
double student2[SCORES] = {0};
double student3[SCORES] = {0};
double student4[SCORES] = {0};
double student5[SCORES] = {0};
double *gradeArray[STUDENTS];
gradeArray[0] = student1;
gradeArray[1] = student2;
gradeArray[2] = student3;
gradeArray[3] = student4;
gradeArray[4] = student5;
for (int studix=0, stduix<STUDENTS; studix++) {
// get the name of the student
for (int gradix=0; gradix<SCORE; gradix++) {
// put the grades in gradeArray[studix][gradix]...
}
//....
}
Yes, I know about 2 D arrays, but I am trying to make explicit how this can be done with "five individual arrays". Clumsy, but I believe this works.
I am writing a program for a homework assignment that calculates rental car rates based on make, days rented and miles driven. Overall the program works except, when the user is prompted for the number of cars to be calculated, the program continues to prompt the user for input after the number has been exceeded. Also, the formatting for the miles is correct for the first vehicle entered but changes for subsequent entries.
Any help with these two issues would be greatly appreciated!
Code:
#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>
#include <cmath>
using namespace std;
int main()
{
// Change the console's background color.
system ("color F0");
// Declare the variables.
char carType;
string brand, f("Ford"), c("Chevrolet");
int counter = 0, cars = 0;
double days, miles, cost_Day, cost_Miles, day_Total;
cout << "Enter the number of cars you wish to enter: ";
cin >> cars;
cin.ignore();
while (counter <= cars)
{
cout << "Enter the car type (F or C): ";
cin >> carType;
cin.ignore();
cout << "Enter the number of days rented: ";
cin >> days;
cin.ignore();
cout << "Enter the number of miles driven: ";
cin >> miles;
cin.ignore();
if (carType == 'F' || carType == 'f')
{
cost_Day = days * 40;
cost_Miles = miles * .35;
day_Total = cost_Miles + cost_Day;
brand = f;
}
else
{
cost_Day = days * 35;
cost_Miles = miles * .29;
day_Total = cost_Miles + cost_Day;
brand = c;
}
cout << "\nCar Days Miles Cost\n";
cout << left << setw(12) << brand << right << setw(6) << days << right << setw(8) << miles
<< fixed << showpoint << setprecision (2) << setw(8) << right << "$" << day_Total << "\n\n";
counter++;
}
system ("pause");
}
You have started counting from 0 int counter = 0, cars = 0;
You then count until you are equal to the number that was entered (the "or equal to" bit of while (counter <= cars)).
As a worked example, if I want 3 entries:
Start: counter = 0, cars = 3.
0 <= 3: true
End of first iteration: counter = 1
1 <= 3: true
End of second iteration: counter = 2
2 <= 3: true
End of third iteration: counter = 3
3 <= 3: true (the "or equal" part of this)
End of FORTH iteration: counter = 4
4 <= 3: false -> Stop
We have completed 4 iterations instead of 3. If we only checked for "strictly less than" (counter < cars), the condition at the end of the third iteration would be false, and we'd have ended there.
The heading of your while loop should be:
while(counter < cars)
rather than
while(counter <= cars)
As you probably gathered from the title I'm having an error initialising the variable 'passNum' in the constructor of my file 'booking.h'
The file contains the booking class for a flight reservation program and I'd like to initialise passNum to 0 because initially there are no passengers on the flight. However I keep getting the message "flight is full" which was in place for the user to see whether there was any space left on the flight or not. SO, to see the error I added a cout in order to see what number was actually stored in passNum. The output was '28080747' however the number changes every time I compile and run.
Booking file...
//Booking class - Scotia Airlines
//Zac Mazs
//This class will reserve a seat for passenger
#include <iostream>
#include <string>
#include "flight.h"
using namespace std;
class Booking{
public:
// default constructor
Booking()
{
int passNum = 0; // initialise passenger number to 0
totalSeats = 24; // total seats on plane
fName = "empty";
sName = "empty";
busName = "empty";
}
// accessor methods
void setPassNum(int p){passNum = p;}
string getFname(){return fName;}
string getSname(){return sName;}
string getBusName(){return busName;}
void addBooking()
{
if (passNum >= totalSeats) // if the number of passengers exceeds 24 then display flight-full message
{
cout << passNum;
cout <<"Flight is full";
}
else
{
cout << "\tBooking Menu \n\n";
cout << "Please select ticket type: \n";
cout << "1- Business \n";
cout << "2- Western Isles \n";
cout << "3- Ordinary \n";
cin >> livesAt;
// This will be used to calc total cost for each passenger dependant on ticket type
if(livesAt == 1)
{
discount = 0.75;
cout << "Please enter your business name\n";
cin >> busName;
}
else if (livesAt == 2)
{
discount = 0.90;
}
else if(livesAt == 3)
{
discount = 1.0;
}
else
{
cout << "Error, please choose 1,2 or 3";
}
// Calculation - Standard ticket price is 60 Beans
tickPrice = 60.0;
tCost = (tickPrice * discount);
bool booked = false;
for(int ROW = 0; ROW < 4 && !booked; ROW++)
{
for(int COL = 0; COL < 6 && !booked; COL++)
{
if(f.isAvailable(ROW,COL) == true)
{
cout << "Please enter your first name \n";
cin >> fName;
cout << "Please enter your second name \n";
cin >> sName;
//create new string fullName from fName and sName
fullName == fName + " " + sName;
f.setName(ROW,COL, fullName);
f.setAvailable(ROW,COL,0);
f.seatArray[ROW][COL].available++;
booked = true;
// increment pass num/decrement totalSeats
totalSeats--;
passNum++;
// Message on screen for customer displaying cost of flight
cout << "*******************************\n";
cout << "\tBooking for "; cout << fName + " " + sName; cout << " confirmed.\n";
cout << "\tTotal cost = " << tCost << " GBP.\n";
}//end of if
}//end of for2
}//end of for1
}//end else
}// End of addBooking function
private:
//Declare all variables
string fName, sName, busName, fullName;
int livesAt, totalSeats;
int passNum;
float discount, tickPrice, tCost;
Flight f;
Seat s;
Passenger p;
};// End of addBooking class
Any thoughts? I really appreciate the help!
Thanks in advance.
In the constructor, passNum is declared locally (it hides the private class-level definition).
Change to:
Booking()
{
/*int*/ passNum = 0; //initialise passenger number to 0
totalSeats = 24; // total seats on plane
fName = "empty";
sName = "empty";
busName = "empty";
}
The problem is the int in
int passNum = 0; // initialise passenger number to 0
You are not assigning to the member variable, you are creating a new local variable with the same name.
To fix, remove the int.