I'm trying to automatically set the number of the given variables, for example:
char subject1[30];
char subject2[30];
char subject3[30];
float grade1;
float grade2;
float grade3;
cout << "Type in your first subject: " ;
cin >> subject1;
cout << "Type in your second subject: ";
cin >> subject2;
cout << "Type in your third subject: ";
cin >> subject3;
cout << "Type in your grade for: " << subject1 << " :";
cin >> grade1;
cout << "Type in your grade for: " << subject2 << " :";
cin >> grade2;
cout << "Type in your grade for: " << subject3 << " :";
cin >> grade3;
float sum = grade1 + grade2 + grade3;
float average = (sum / 3);
cout << "AVERAGE GRADE";
cout << "************************************" << endl;
cout << subject1 << grade1 << endl;
cout << subject2 << grade2 << endl;
cout << subject3 << grade3 << endl;
cout << "====================================" << endl;
cout << "Average: " << average << endl;
return 0;
The code that calculates it works but I was wondering as how do I put the 3 grades that user inputed. So I don't have to go edit the calculation part every time I add another subject. I'm not sure if I explained well as to what I meant but I hope you understand.
A simple solution would be to store everything in a vector (that's preferred most of the time over the char array you used) an then just loop for the amount of subjects you have.
#include <vector> // need to inlcude this to be able to use vector
#include <iostream>
const int numSubjects = 3;
std::vector<std::string> prefix{"first", "second", "third"};
std::vector<std::string> subjects(numSubjects);
std::vector<float> grades(numSubjects);
for(int i = 0; i < numSubjects; i++) {
std::cout << "Type in your " << prefix[i] << " subject: ";
std::cin >> subjects[i];
std::cout << "Type in your grade for " << subjects[i] << ": ";
std::cin >> grades[i];
}
//afterwards do the calculations
Note that I initialized the vectors with a size of numSubjects that way you can access and write to indices of the vector with the [] operator. If you don't initialize vector with a size then you can use push_back() to insert elements.
Related
I am trying to store multiple int into a vector by having the user input the grade they have received. However I do believe there is a more simplified version of trying to do this. Would it be better to have separate functions? Is there anyone who can guide me in the right direction?
#include <iostream>
#include <vector>
#include <numeric>
using namespace std;
int main() {
cout << "Welcome to the Grade Calculator! \n"
<< "What is the student's full name? ";
string student_name;
getline(cin,student_name);
cout << "\nPlease input the points earned for each assignment.";
vector<int> student_grades(8);
cout << "\nLab 2: ";
cin >> student_grades[0];
cout << "Lab 3: ";
cin >> student_grades[1];
cout << "Lab 4: ";
cin >> student_grades[2];
cout << "Lab 5: ";
cin >> student_grades[3];
cout << "Lab 6: ";
cin >> student_grades[4];
cout << "Lab 7: ";
cin >> student_grades[5];
cout << "Lab 8: ";
cin >> student_grades[6];
cout << "Lab 9: ";
cin >> student_grades[7];
cout << "Lab 10: ";
cin >> student_grades[8];
//Finding sum of the grades
int sum_of_grades = accumulate(student_grades.begin(),student_grades.end(),0);
//Console Output
cout << '\n'<< student_name << " has earned " << sum_of_grades << " points in the course, so far." << endl;
cout << "\nThere are 2000 points possible in this course." << endl;
cout << "\nInput the anticpated score for the final project (200 points possible): ";
int anticipated_score;
cin >> anticipated_score;
int total_score = sum_of_grades+anticipated_score;
cout << "Total Projected Assignment Points: " << total_score << endl;
cout << "\nFinal Exam Score Needed for Final Course Grade (1000 Points Possible)"
<< "\nTo Earn an A, need at least: " << 1800 - total_score << " points, for a total of: 1800"
<< "\nTo Earn a B, need at least: " << 1600 - total_score << " points, for a total of: 1600"
<< "\nTo Earn a C, need at least: " << 1400 - total_score << " points, for a total of: 1400"
<< "\n To Earn a D, need at least: " << 1200 - total_score << " points, for a total of: 1200" << endl;
return 0;
}
You can use a for-loop:
for(int i = 0; i < 8; ++i){
cout << "\nLab " << i+2 << ": ";
cin >> student_grades[i];
}
This code is essentially equivalent to what you wrote in your program; it loops through all possible indices, prompting the user to input numbers into the vector.
I am to create an application that takes at least 5 employees i.d, names, pay rate, and hours. And then I am to add the pay rate and the hours together to show the gross pay for each employee at the end of the initial inquiries. I am stuck on how to add it in the vector please help!
** Here is the assignment that our instructor gave us **
http://itweb.fvtc.edu/ag/?u=3&f=cpp-assignment4
I've added a vector and added all the essential information for the employee
#include <iostream>
#include <conio.h>
#include <string>
#include <vector>
using namespace std;
struct Employee
{
int id;
string firstName;
string lastName;
float payRate;
int hours;
};
int main()
{
/*========= other way of adding employee information ==========*/
/*const int NUM_EMPLOYEE = 5;
Employee employee[NUM_EMPLOYEE];
for (int i = 0; i < 5; i++)
{
cout << "ID of employee " << (i + 1) << ": ";
cin >> employee[i].id;
cout << "First Name of employee " << (i + 1) << ": ";
cin >> employee[i].firstName;
cout << "Last Name of employee " << (i + 1) << ": ";
cin >> employee[i].lastName;
cout << "Pay rate for employee " << (i + 1) << ": ";
cin >> employee[i].payRate;
cout << "Hours worked " << (i + 1) << ": ";
cin >> employee[i].hours;
}*/
/*========= End of other way of adding employee information ==========*/
vector<Employee> employees;
char Another = 'y';
while (Another == 'y' || Another == 'Y')
{
Employee e;
cout << "Enter employee ID: \n";
cin >> e.id;
cout << "Enter employee first name: \n";
cin >> e.firstName;
cout << "Enter employee last name: \n";
cin >> e.lastName;
cout << "Enter employee pay rate: \n";
cin >> e.payRate;
cout << "Enter employee hours worked: \n";
cin >> e.hours;
employees.push_back(e);
cout << "Another? (y/n): \n";
cin >> Another;
}
float sum = 0;
vector<Employee>::iterator it = employees.begin();
for (; it != employees.end(); it++)
{
cout << "ID of employee: \n" << it->id << ": \n"
<< "Employees name: \n" << it->firstName << " " << it->lastName << ": \n"
<< "Employee pay rate: \n" << it->payRate << ": \n"
<< "Employee hours worked: \n" << it->hours << "\n";
}
float avg = sum / employees.size();
Employee e;
/*cout << " ID of employees: \n" << e.id;
cout << " Name of employees: \n" << e.firstName << " " <<
e.lastName;*/
cout << "Gross pay of employees: \n" << avg;
_getch();
return 0;
}
Show Id, names, and gross pay of all employees to user
vector<Employee> employees;
char Another = 'y';
while (Another == 'y' || Another == 'Y')
{
Employee e;
cout << "Enter employee ID: \n";
cin >> e.id;
cout << "Enter employee first name: \n";
cin >> e.firstName;
cout << "Enter employee last name: \n";
cin >> e.lastName;
cout << "Enter employee pay rate: \n";
cin >> e.payRate;
cout << "Enter employee hours worked: \n";
cin >> e.hours;
employees.push_back(e);
cout << "Another? (y/n): \n";
cin >> Another;
}
float sum = 0;
vector<Employee>::iterator it = employees.begin();
cout << "ID" << "\t" << "First Name" << "\t" << "Last Name" << "\t" << "Pay rate" << "\t" << "Hours" << "\t" << "Gross Pay" << "\n" ;
for (; it != employees.end(); it++)
{
float grossPay = it->payRate * it->hours;
cout << it->id << "\t" << it->firstName << "\t\t" << it->lastName << "\t\t" << it->payRate << "\t\t"
<< it->hours << "$" << "\t" << grossPay << "\n";
sum += grossPay;
}
cout << "The gross pay for all employee is: " << "$" << sum;
_getch();
return 0;
}
//This is what i got so far. But if I want to make the application ask the user to input how many employee they want to enter into the database how do i do that? would it be like this?
int EMPLOYEE_NUM[][] // ??
I'm trying to complete an assignment but I'm having difficulty with the math expressions and variables in general. I'm trying to make a program that takes user info on groceries and then outputs a receipt. Here is my code.
#include <iostream>
#include <string>
using namespace std;
int main()
{
//user input
string firstItem, secondItem;
float firstPrice, secondPrice;
int firstCount, secondCount;
double salesTax = 0.08675;
double firstExt = firstPrice * firstCount;
double secondExt = secondPrice * secondCount;
double subTotal = firstExt + secondExt;
double tax = subTotal * salesTax;
double total = tax + subTotal;
//user input
cout << "What is the first item you are buying?" << endl;
getline(cin, firstItem);
cout << "What is the price of the " << firstItem << "?" << endl;
cin >> firstPrice;
cout << "How many " << firstItem << "s?" <<endl;
cin >> firstCount;
cin.ignore();
cout << "What is the second item you are buying?" << endl;
getline(cin, secondItem);
cout << "what is the price of the " << secondItem << "?" << endl;
cin >> secondPrice;
cout << "How many " << secondItem << "s?" << endl;
cin >> secondCount;
// receipt output
cout << "1st extended price: " << firstExt << endl;
cout << "2nd extended price: " << secondExt << endl;
cout << "subtotal: " << subTotal << endl;
cout << "tax: " << tax << endl;
cout << "total: " << total << endl;
return 0;
}
The program output either 0 for all or negatives.
Your calculations must go after you read in the values, not before. You're making your calculations based on uninitialized variables.
A declaration and initialisation like
double firstExt = firstPrice * firstCount;
initialises firstExt to be the product of the current values AT THAT POINT of firstPrice and firstCount.
It doesn't set up some magic so that the value of firstExt is recalculated whenever the values of firstPrice or firstCount are changed.
In your case, firstPrice and firstCount are uninitialised variables when you do this. Accessing values of uninitialised variables of type int gives undefined behaviour.
What you need to do is something like
cout << "What is the price of the " << firstItem << "?" << endl;
cin >> firstPrice;
cout << "How many " << firstItem << "s?" <<endl;
cin >> firstCount;
firstExt = firstPrice*firstCount; // do the calculation here
If the value of firstExt is not needed until this point, you can declare it here instead;
double firstExt = firstPrice*firstCount; // do the calculation here
which means any earlier use of firstExt will give a compiler diagnostic.
My issue is that I have set up an array to store totals that were calculated from values read from a file. These stored totals are then added together to find the over all average.
This issue is stemming from a 'cin' at the beginning of the program where the user inputs a number and that number is supposed to drive the program by setting how many times the program loops and how many modules are inside the array. The array does not seem to work properly no matter how much I try.
#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;
int total = 0;
double choice;
ofstream outFile;
double numStud=1;
cout << "Enter student ID number, Quiz 1 Grade, Quiz 2 Grade , Quiz 3 Grade, Quiz 4 Grade" << endl;
outFile.open("StudentGrades.txt");
cout << "How many students would you like to enter?" << endl;
cin >> numStud;
for (int x = 0; x < numStud; 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";
}
outFile.close();
/*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;
}*/
}
ifstream inFile;
inFile.open("StudentGrades.txt");
int sTotal;
int total[numStud];
while (inFile >> studentID >> quiz1 >> quiz2 >> quiz3 >> quiz4)
{
//cout << studentID << " " << quiz1 << " " << quiz2 << " " << quiz3 << " " << quiz4 << endl;
total = (quiz1 + quiz2 + quiz3 + quiz4);
sTotal = total[numStud];
double avg = total / 4;
}
system("pause");
return 0;
}
int total[numStud]; is a variable length array and is not standard in C++. If you need an array and you don't know what the size will be then you should use a std::vector. A vector can be used almost exactly as an array can. For example you could would become:
int total;
std::vector<int> studentTotal;
while (inFile >> studentID >> quiz1 >> quiz2 >> quiz3 >> quiz4)
{
//cout << studentID << " " << quiz1 << " " << quiz2 << " " << quiz3 << " " << quiz4 << endl;
studentTotal.push_back(quiz1 + quiz2 + quiz3 + quiz4); // insert into the vector at the end
total += studentTotal.back(); // get last inserted element
}
I have a problem with my code, every time I loop it with the answer 'y'(Yes) it loops to infinity?
I'm trying to make a loan calculator and every time the user is done calculating with a transaction and wants to reset, and do another calculation if he enters in a value 'y', and if he enters 'n' the program will end.
Here's my code so far:
#include <iostream>
#include <string>
#include <iomanip>
#include <cmath>
using namespace std;
int main() {
char ans = 'y';
do {
string name;
int Months;
int n;
double LoanAmount, Rate, MonthlyInterest, TotalLoanAmount, MonthlyAmortization, OutstandingBalance;
cout << fixed << showpoint;
cout << "Enter Name of Borrower: ";
getline(cin, name);
cout << "Enter Loan Amount: ";
cin >> LoanAmount;
cout << "Enter Number of Months to Pay: ";
cin >> Months;
cout << "Enter Interest Rate in Percent(%): ";
cin >> Rate;
cout << setprecision(2);
MonthlyInterest = LoanAmount * Rate;
TotalLoanAmount = LoanAmount + (MonthlyInterest * Months);
cout << "Monthly Interest: " << MonthlyInterest << endl
<< "Total Loan Amount with interest: " << TotalLoanAmount << endl;
cout << setw(100)
<< "\n\tSUMMARY OF OUTSTANDING INSTALLMENT" << endl
<< "\tName of Borrower: " << name
<< "\n\nMonth\t\tMonthly Amortization\t\tOutstanding Balance"
<< "\n";
for(n = 1; n <= Months; n++) {
MonthlyAmortization = TotalLoanAmount / Months;
OutstandingBalance = TotalLoanAmount - MonthlyAmortization;
cout << n << "\t\t" << MonthlyAmortization << "\t\t\t" << n - 1 << OutstandingBalance << endl;
}
cout << "\nEnd of Transaction";
cout << "Do you want to compute another transaction?[y/n]?" << endl;
cin >> ans;
}
while(ans == 'y');
}
After your cin>>ans, add these two lines :
cin.clear();
cin.sync();
That usually fixes a lot of the infinite looping problems I get with cin.
Also, I would recommend against initializing ans as 'y' when you declare it. I don't think this is causing you problems but it's an uncessesary thing.
You seem to expect pressing y and enter to register as only 'y'. If you want to get the input of just one character have a look at std::cin.get(char)