I need help in a simple way of solving a part of my code that i cant seem to make it work.The point of my "assignment" is that everything must try to be in one class.Now the problem i am having is at a part of my code where it is suppose to "print" the n number of products meaning that it displays what you have inputted in the void get() part,but the problem i cant seem to resolve is it only prints the last name,amount,weight of the product and not everything written.
class Class
{
public:
string name;
int n, amount;
float weight;
void market()
{
cout << "Give the number of products you want to get at Market : " << endl;
cin >> n;
}
void get()
{
for (int i = 0; i < n; i++)
{
cout << "Give product name,amount and weight : " << endl;
cin >> name >> amount >> weight;
}
}
void print()
{
cout << "\nProduct display:\n" << endl;
for (int i = 0; i < n; i++)
{
cout << name << " - " << amount << " , " << weight << " kg" << endl;
cout << "------------------------" << endl;
}
};
};
The main part.
int main()
{
Class market;
market.market();
market.get();
market.print();
}
You're actually overwriting name, amount and weight. You have to make use of something similar to std::vector:
class Class {
public:
std::vector<string> names;
// Same for others
When you get them from std::cin you have to push them into the vector:
names.push_back(name);
amounts.push_back(amount);
weights.push_back(weight);
When printing you loop over the vectors:
for (int i = 0; i < n; i++) {
cout << names[i] << " - " << amounts[i] << " , " << weights[i] << " kg" << endl;
cout << "------------------------" << endl;
}
You must use a std::vector<TYPE> (example 1), or array for holding multiple data in a single variable (example 2).
Example 1
Since you've been coding in C++ programming language, it's highly recommended to use std::vector<> for best results.
Consider the class example (read comments too):
int count = 0; // PRIVATE SECTION
char ask;
std::vector<std::string> name;
std::vector<int> amount;
std::vector<float> weight;
std::string tName; // temp variables
int tAmount;
float tWeight;
public:
void market()
{
cout << "WELCOME!" << endl; // nothing's required with vector
}
void get()
{
do {
cout << "Give product name, amount and weight : " << endl;
cin >> tName >> tAmount >> tWeight; // getting temporary variables
name.push_back(tName); // assigning
amount.push_back(tAmount);
weight.push_back(tWeight);
count++;
cout << "Add more? (Y/n): "; // add more? Go on if yes...
cin >> ask;
} while (ask == 'Y' || ask == 'y');
}
void print()
{
cout << "\nProduct display:\n"
<< endl;
for (int i = 0; i < count; i++)
{
cout << name[i] << " - " << amount[i] << " , " << weight[i] << " kg" << endl;
cout << "------------------------" << endl;
}
}
Sample Output
WELCOME!
Give product name, amount and weight :
ABC 12 55.5
Add more? (Y/n): y
Give product name, amount and weight :
SSD 33 43.2
Add more? (Y/n): n
Product display:
ABC - 12 , 55.5 kg
------------------------
SSD - 33 , 43.2 kg
------------------------
Example 2
You can do the same thing just with few modifications, but having static number isn't considered dynamic. You can use arrays for your program as stated below.
Rather than:
string name;
int n, amount;
float weight;
Consider const int MAX = 1024; and use (class variables must be visible only inner the class and nowhere else):
private: // declare on top of the class ("private:" is by default and redundant)
string name[MAX];
int n, amount[MAX];
float weight[MAX];
Edited & working example class:
void get()
{
for (int i = 0; i < n; i++)
{
cout << "Give product name,amount and weight : " << endl;
cin >> name[i] >> amount[i] >> weight[i];
}
}
void print()
{
cout << "\nProduct display:\n"
<< endl;
for (int i = 0; i < n; i++)
{
cout << name[i] << " - " << amount[i] << " , " << weight[i] << " kg" << endl;
cout << "------------------------" << endl;
}
}
Sample Output
Give the number of products you want to get at Market :
2
Give product name,amount and weight :
ABC 25 102
Give product name,amount and weight :
BDE 22 333
Product display:
ABC - 25 , 102 kg
------------------------
BDE - 22 , 333 kg
------------------------
Related
I have this program that is barely started:
#include <iostream>
#include <iomanip>
#include <ctime>
#include <string>
using namespace std;
class Grade
{
public:
string studentID;
int userChoice = 0;
int size = 0;
double* grades = new double[size]{0};
};
void ProgramGreeting(Grade &student);
void ProgramMenu(Grade& student);
string GetID(Grade& student);
int GetChoice(Grade& student);
void GetScores(Grade& student);
int main()
{
Grade student;
ProgramGreeting(student);
ProgramMenu(student);
}
// Specification C1 - Program Greeting function
void ProgramGreeting(Grade &student)
{
cout << "--------------------------------------------" << endl;
cout << "Welcome to the GPA Analyzer! " << endl;
cout << "By: Kate Rainey " << endl;
cout << "Assignment Due Date: September 25th, 2022 " << endl;
cout << "--------------------------------------------" << endl;
GetID(student);
cout << "For Student ID # " << student.studentID << endl;
}
void ProgramMenu(Grade &student)
{
cout << "--------------------------------------------" << endl;
cout << setw(25) << "Main Menu" << endl;
cout << "1. Add Grade " << endl;
cout << "2. Display All Grades " << endl;
cout << "3. Process All Grades " << endl;
cout << "4. Quit Program." << endl;
cout << "--------------------------------------------" << endl;
GetChoice(student);
}
string GetID(Grade &student)
{
cout << "Enter the student's ID: ";
cin >> student.studentID;
if (student.studentID.length() != 8) {
cout << "Student ID's contain 8 characters ";
GetID(student);
}
return student.studentID;
}
int GetChoice(Grade &student)
{
cout << "Enter your selection: ";
cin >> student.userChoice;
if (student.userChoice == 1) {
GetScores(student);
}
else if (student.userChoice == 2)
{
}
else if (student.userChoice == 2)
{
}
else if (student.userChoice == 4)
{
exit(0);
}
else
{
cout << "Please enter 1, 2, 3 or 4" << endl;
GetChoice(student);
}
}
void GetScores(Grade &student)
{
int count = 0;
double score = 0;
cout << "How many test scores would you like to enter for ID# "
<< student.studentID << "? ";
cin >> student.size;
while (count != student.size) {
cout << "Enter a grade: ";
cin >> score;
for (int i = 0; i < student.size; i++) {
student.grades[i] = score;
}
count++;
}
for (int i = 0; i < student.size; i++) {
cout << student.grades[i] << " ";
}
}
I am trying to make sure my array is recording all test scores, but when I output the array in my GetScore function, each element in the array is the same or equal to the last score I entered. For example, if I choose 3 for size and then enter three values of 99.2 86.4 90.1, all three elements will read 90.1.
Why is this happening?
Your Grade class is allocating an array of 0 double elements (which is undefined behavior), and then your GetScores() function does not reallocate that array after asking the user how many scores they will enter, so you are writing the input values to invalid memory (which is also undefined behavior).
Even if you were managing the array's memory correctly (ie, by using std::vector instead of new[]), GetScores() is also running a for loop that writes the user's latest input value into every element of the array, instead of just writing it to the next available element. That is why your final output displays only the last value entered in every element. You need to get rid of that for loop completely.
Try something more like this instead (there are several other problems with your code, but I'll leave those as separate exercises for you to figure out):
class Grade
{
public:
...
int size = 0;
double* grades = nullptr;
};
...
void GetScores(Grade &student)
{
int size = 0;
double score = 0;
cout << "How many test scores would you like to enter for ID# " << student.studentID << "? ";
cin >> size;
if (student.size != size) {
delete[] student.grades;
student.grades = new double[size]{0};
student.size = size;
}
for(int i = 0; i < size; ++i) {
cout << "Enter a grade: ";
cin >> score;
student.grades[i] = score;
}
for (int i = 0; i < size; ++i) {
cout << student.grades[i] << " ";
}
}
Alternatively:
#include <vector>
...
class Grade
{
public:
...
vector<double> grades;
};
...
void GetScores(Grade &student)
{
size_t size = 0;
double score = 0;
cout << "How many test scores would you like to enter for ID# " << student.studentID << "? ";
cin >> size;
student.grades.resize(size);
for (size_t i = 0; i < size; ++i) {
cout << "Enter a grade: ";
cin >> score;
student.grades[i] = score;
}
/* alternatively:
student.grades.clear();
for (size_t i = 0; i < size; ++i) {
cout << "Enter a grade: ";
cin >> score;
student.grades.push_back(score);
}
*/
for (size_t i = 0; i < size; ++i) {
cout << student.grades[i] << " ";
}
}
I removed my for loop from my while loop.
void GetScores(Grade &student)
{
int count = 0;
double score = 0;
cout << "How many test scores would you like to enter for ID# "
<< student.studentID << "? ";
cin >> student.size;
while (count != student.size) {
cout << "Enter a grade: ";
cin >> score;
student.grades[count] = score;
count++;
}
for (int j = 0; j < student.size; j++) {
cout << student.grades[j] << " ";
}
}
I was given a task to write an example of derived class. But In my program, something strange is happening with the roll numbers.
Also, when this program is compiled in g++.
When I used char [] and gets() to store the strings and input values into them, it didn't allow me to enter the value for collname.
When I use string and cin, I get some strange values while asking for marks.(Check the attached image).
#include<iostream>
#include<conio.h>
using namespace std;
class uni
{
private:
int rollno[100], i, flag;
int intermarks[100];;
int theorymarks[100];
void settheorymarks();
protected:
int numstud;
void setintermarks();
void issurno();
public:
void prepres();
void showres(string collname);
};
class college : public uni
{
private:
string collname;
public:
college(int N)
{
numstud = N;
issurno();
}
void enter_marks();
void disp();
};
void uni::issurno()
{
for (i = 0; i < numstud; i++)
rollno[i] = 1024+i;
cout << "Roll numbers issued!" << endl;
}
void uni::settheorymarks()
{
cout << "Enter theory marks for: " << endl ;
for(i = 0; i < numstud; i++)
{
cout << i+1 << ".) Roll number: " << rollno << " : ";
cin >> theorymarks[i];
}
cout << endl << endl << "Theory marks recorded!" << endl;
}
void uni::setintermarks()
{
cout << "Enter inter marks for: " << endl ;
for(i = 0; i < numstud; i++)
{
cout << i+1 << ".) Roll number: " << rollno << " : ";
cin >> intermarks[i];
}
cout << endl << endl << "Internal marks recorded!" << endl;
}
void uni::prepres()
{
settheorymarks();
}
void uni::showres(string colnam)
{
cout << "College: " << colnam << endl;
cout << "__________________________Result___________________________" << endl;
cout << "s. No.\tRoll no\tInternal\tTheory" << endl;
for(i = 0; i < numstud; i++)
cout << i+1 << "\t" << rollno[i] << '\t' << intermarks[i] << "\t" << theorymarks[i] << endl;
cout << endl << "End of result!" << endl;
}
void college::disp()
{
showres(collname);
}
void college::enter_marks()
{
cout << "Enter the college name: ";
cin >> collname;
setintermarks();
prepres();
}
int main()
{
int n;
cout << "Enter number of stufents: ";
cin >> n;
college c(n);
c.enter_marks();
c.disp();
return 0;
}
I feel that I've made a stupid mistake somewhere.
PS: In school, I was forced to use turbo C++ (One of the oldest compilers).
You just forget the [i] after rollno in the two lines like:
cout << i+1 << ".) Roll number: " << rollno[i] << " : ";
There are a few other things I would ask you to improve if I was your supervisor/teacher:
always use expressive variable and method names. Avoid any abbreviations.
why is there the arbitray offset of 1024 in rollno? If this is just "obfuscation" remove it...
Unclear: why is setintermarks called inside enter_marks but settheorymarks in prepres ?
typo in "stufents"
How can I make the program display only cars that have 5 seats, for now no matter what, it shows all cars that I write infos about them, for example if I write in the console that there are 3 cars and give information about them and say that one has 2 seats and the others have 5 after I run the program it still displays all 3 of them. Any idea of how can I display only cars with 5 seats? Can I somehow use the quicksort() function ?
#include <iostream>
using namespace std;
struct Car
{
int no_seats;
int year;
char brand[20];
char color[20];
float horse_power;
};
void read_cars(Car C[], int &n)
{
int i;
cout << "Number of parked cars "; cin >> n;
for(i=1; i<=n; i++)
{
cout << "Brand " ; cin >> M[i].brand;
cout << "The year it was made in " ; cin >> M[i].year;
cout << "Color " ; cin >> M[i].color;
cout << "Power " ; cin >> M[i].horse_power;
cout << "Number of seats " ; cin >> M[i].no_seats;
}
}
void display_cars(Car C[], int n)
{
int i;
for(i=1; i<=n; i++)
{
cout << "Brand " ; cout << M[i].brand << endl;
cout << "The year it was made in " ; cout << M[i].year << endl;
cout << "Color " ; cout << M[i].color << endl;
cout << "Power " ; cout << M[i].horse_power << endl;
cout << "Number of seats " ; cout << M[i].no_seats << endl;
}
}
int main()
{
Car C[50];
int n;
read_cars(M, n);
display_cars(M, n);
return 0;
}
You need to add a condition in the loop:
void display_cars(Car C[], int n)
{
int i;
for(i=1; i<=n; i++)
{
if(M[i].no_seats == 5) // <- like this
{
cout << "Brand " ; cout << M[i].brand << endl;
cout << "The year it was made in " ; cout << M[i].year << endl;
cout << "Color " ; cout << M[i].color << endl;
cout << "Power " ; cout << M[i].horse_power << endl;
cout << "Number of seats " ; cout << M[i].no_seats << endl;
}
}
}
Other notes:
Your n can only go up to 49 - remember that. That also means that you are wasting an element at M[0] (yes arrays are zero based in C++).
Prefer to use std::vector<Car> C over an array of fixed size. A std::vector grows as you push_back more and more elements into it - and it keeps track of the number of contained elements, so you do not need to pass the size of the vector around. C.size() would tell you the number of elements.
void display_cars(const std::vector<Car>& C)
{
std::cout << "There are " << C.size() << " cars in the vector\n";
for(const Car& a_car : C) // a range based for-loop
{
if(a_car.no_seats == 5) // a_car will be a reference to each car in the loop
{
// use "a_car" to display info about one particular car
}
}
}
I've run into some trouble in my programming book while completing an exercise to do with BankAccounts. The question asks:
Create a main() function that declares an array of 10 BankAccount objects. After
the first BankAccount object is entered, ask the user if he or she wants to continue. Prompt the user for BankAccount values until the user wants to quit or enters 10 BankAccount objects, whichever comes first. For each BankAccount entered, display the BankAccount details. Then prompt the user for a term with a value between 1 and 40 inclusive. Continue to prompt the user until a valid value is entered. Then pass the array of BankAccount objects, the count of valid objects in the array, and the desired term to a function that calculates and displays the values of each of the BankAccounts after the given number of years at the standard interest rate.
I have to use 3 public functions to complete this task. I only start running into problems when I try to computeInterest(). If I attempt to pass the term and count to the function and set it up in 2 for loops I will only receive the numbers and balances for a single object. I guess what i'm asking is: How do I get the program to call computeInterest and run through for each BankAccount object?
At the moment my code is set so that it will compile and run perfectly well, however, the question asks for the term and count to be sent to the function while I'm only sending the term.
I'm not sure if I'm sending the array of objects to the function? Which may be whats causing the trouble. This has been grinding my brain for quite a few days now :(. Any help/pointers are greatly appreciated!
#include<iostream>
#include<string>
using namespace std;
// Declaration Section
class BankAccount
{
private:
int accNum;
double accBal;
const static double intRate;
public:
void enterAccountData(int, double);
void computeInterest(int);
void displayAccount();
};
// Implementation Section
const double BankAccount::intRate = 0.03;
void BankAccount::enterAccountData(int num, double bal)
{
const int MIN_ACC = 1000, MAX_ACC = 9999, MIN_BAL = 0,
MAX_BAL = 100000;
cout << "Enter account number: ";
cin >> num;
while (num < MIN_ACC || num > MAX_ACC)
{
cout << "ERROR: Account number must be between " << MIN_ACC <<
" - " << MAX_ACC << ".\n" << "Enter account number: ";
cin >> num;
}
cout << "Enter account balance: $";
cin >> bal;
while (bal < MIN_BAL || bal > MAX_BAL)
{
cout << "ERROR: Account balance must be positive and less than $" <<
MAX_BAL << ".\n" << "Enter account balance: $";
cin >> bal;
}
accNum = num;
accBal = bal;
}
void BankAccount::computeInterest(int YR)
{
int x;
double interest;
for (x = 0; x < YR; ++x)
{
interest = accBal * intRate;
accBal = accBal + interest;
cout << "Account# " << accNum <<
", Balance: $" << accBal << ", Interest: " <<
intRate << endl;
}
cout << endl;
}
void BankAccount::displayAccount()
{
cout<<"Account: " << accNum <<", Balance: $" << accBal <<
", Interest: " << intRate << endl << endl;
}
int main()
{
const int END = -999, MAX_ACCOUNTS = 10, CONTINUE = 1, MIN_TERM = 1,
MAX_TERM = 40;
int i, x, count = 0, num = 0, term = 0;
double bal = 0;
BankAccount accounts[MAX_ACCOUNTS];
do
{
count++;
accounts[count - 1].enterAccountData(num, bal);
accounts[count - 1].displayAccount();
cout << "Enter " << CONTINUE << " to proceed, or " << END << " to stop: ";
cin >> i;
if (i == END || count == MAX_ACCOUNTS)
{
cout << "Enter the term of the accounts (" << MIN_TERM <<
"-" << MAX_TERM << "): ";
cin >> term;
while (term < MIN_TERM || term > MAX_TERM)
{
cout << "ERROR: Term must be between " << MIN_TERM <<
" - " << MAX_TERM << " inclusive.\n" <<
"Enter term of the accounts (" << MIN_TERM <<
"-" << MAX_TERM << "): ";
cin >> term;
}
for (x = 0; x < count; ++x)
accounts[x].computeInterest(term);
}
} while (i != END && count != MAX_ACCOUNTS);
}
You are already doing it in
for (x = 0; x < count; ++x)
accounts[x].computeInterest(term);
If really necessary, you can move that particular piece of code in a separate function, one that accepts 3 parameters: the array accounts, the count and the term.
The way you have setup the BankAccount class is that each object calculates its own interest.
Since you have several such objects, you can ask each one to compute its own interest.
Hope this helps!Let me know if there are any other questions :)
I need to be able to have the objects within the array be valid or invalid/ have value or have no value.
So if the user entered only 5 accounts out of 10 possible, it would throw away the last 5 that do not have any value what so ever, so as to not ask for a computed interest for an account that doesn't exist.
How do I do this?
#include <iostream>
#include <iomanip>
using namespace std;
class BankAccount
{
private:
int accountNum;
double accountBal;
static const double annualIntRate;
public:
void enterAccountData(int, double);
void computeInterest();
void displayAccount();
};
//implementation section:
const double BankAccount::annualIntRate = 0.03;
void BankAccount::enterAccountData(int number, double balance)
{
cout << setprecision(2) << fixed;
cout << "Enter the account number " << endl;
cin >> number;
accountNum = number;
while(number < 0 || number < 1000)
{
cout << "Account numbers cannot be negative or less than 1000 " <<
"Enter a new account number: " << endl;
cin >> number;
}
cout << "Enter the account balance " << endl;
cin >> balance;
accountBal = balance;
while(balance < 0)
{
cout << "Account balances cannot be negative. " <<
"Enter a new account balance: " << endl;
cin >> balance;
}
return;
}
void BankAccount::computeInterest()
{
const int MAX_ACCOUNTS = 10;
const int MONTHS_IN_YEAR = 12;
int months;
double rate = 0;
int counter = 0;
cout << endl << "How many months will the account be held for? " << endl;
cin >> months;
counter = 0;
do
{
accountBal = accountBal * annualIntRate + accountBal;
counter++;
}while(months > counter);
cout << endl << "Account # " << accountNum << " 's balance is:$" << accountBal << endl;
}
int main()
{
const int QUIT = 0;
const int MAX_ACCOUNTS = 10;
int counter;
int input;
int number = 0;
double balance = 0;
BankAccount accounts[MAX_ACCOUNTS];
//BankAccount display;
counter = 0;
do
{
accounts[counter].enterAccountData(number, balance);
cout << " Enter " << QUIT << " to stop, or press 1 to proceed.";
cin >> input;
counter++;
}while(input != QUIT && counter != 10);
for(counter = 0; counter < MAX_ACCOUNTS; counter++)
{
accounts[counter].computeInterest();
}
system("pause");
return 0;
}
You should try tonarrow down your questions to just what you are really asking, this is a little confusing to look at.
After the first loop, have it "remember" what value for counter it managed to reach, and then in the second loop only iterate up to that, instead of up to MAX_ACCOUNTS.
And converting from months to years is just dividing by 12 no?
It seems you have skipped the chapters about Arrays. Re-read it!
ps. surely 0 < 1000 while(number < 0 || number < 1000)
void BankAccount::enterAccountData(int number, double balance). What is the need for the two arguments ? Take the input directly for the member variables. Unnecessary operations are commented. This would also do the job -
void BankAccount::enterAccountData()
{
cout << setprecision(2) << fixed;
cout << "Enter the account number " << endl;
cin >> accountNum; // Take input directly to accountNum
// accountNum = number; // No need of this assignment
while(accountNum < 0 || accountNum < 1000)
{
cout << "Account numbers cannot be negative or less than 1000 " <<
"Enter a new account number: " << endl;
cin >> accountNum;
}
cout << "Enter the account balance " << endl;
cin >> accountBal;
// accountBal = balance; // Unnecessary assignment
while(accountBal < 0)
{
cout << "Account balances cannot be negative. " <<
"Enter a new account balance: " << endl;
cin >> accountBal;
}
// return; // What is the need of this return statement? Method signature says
// it doesn't return anything.
}
When you think of declaring variables, think of whether they are necessary. Unnecessary declaring and assigning the variables make the problem looks complex and is the source of confusion. Think simple :)