I'm relative new to C++ and I'm sure there is probably plenty on information on here. Unfortunately, I don't seem to understand it.
I have a class called Account with variables called Number and Balance. The Member Name is given by the User through cin and represent an Account Number. I was able to dynamically create an object through cin. and give their variables a value through cin. However, I'm not able to give the variables a value or ask for the values in the class through cin.
I have been looking for hours and just cannot figure it out. Any help is appreciated. Thanks guys.
Here is my code:
class Account {
public:
int Number;
int Balance;
};
int main() {
int Nmbr;
int Bal;
cin >> Nmbr;
cin >> Bal;
Account Nmbr; // create the object
Nmbr.Number = Nmbr; // add the cin input 'Nmbr' to the variable Number - FALSE
Nmbr.Balance = Bal; // add the cin input 'Bal' to the variable Balance - FALSE
cout << Nmbr.Number << endl; // display Account.Number - FALSE
cout << Nmbr.Balance << endl; //display Account.balance - FALSE
}
Ok I think something like this is what you are after:
account.h:
class Account
{
public:
Account();
Account(int number);
int Number;
int Balance;
};
account.cpp:
#include "account.h"
Account::Account() {}
Account::Account(int number) {
this->Number = number;
}
So then in main you would do something like:
#include <iostream>
#include "account.h"
#include <vector>
const size_t MAXNUM = 5;
int main()
{
std::vector<Account*> allAccounts;
for (int accntNumber = 0; accntNumber < MAXNUM; accntNumber++) {
Account* account = new Account(accntNumber);
allAccounts.push_back(account);
}
// Then later do other stuff:
for (int accntNumber = 0; accntNumber < MAXNUM; accntNumber++) {
Account* checkAccount = allAccounts.at(accntNumber);
std::cout << "Account # = " << checkAccount->Number << std::endl;
}
return 0;
}
Edit: added an account class with a class creator based on the account number.
Related
I'm trying to write a program that simulates an ATM. The user can log in with a pin and account number, check their account balance, and make a withdrawal. I'm having trouble initializing the array that contains the account information, here's what I have so far:
#include <iostream>
#include <string>
using namespace std;
class Account
{
private: int accountNum;
string accountPin;
double balance;
void setPin();
void setAccountNum();
public: Account ()//default constructor
{
accountNum = -1;
accountPin = -1;
balance = 0.0;
};
Account (int accountNum, string accountPin, double balance)
//overloaded construtor
{
accountNum = accountNum;
accountPin = accountPin;
balance = balance;
};
void setAccountBalance(double bal);//acc balance setter
int getAccountNum() //acc balance getter
{
return balance;
}
bool confirmPin(string)//confirm pin# func
{
}
void updateBalance(double)
};
int main ()
{
int option;
//accounts array
Account account[]= (123, "abc123", 100.00), (456, "def456", 50.00),(789,"ghi789", 500.63);
//login code, unfinished
cout << "LOGIN\nEnter Account#: "<< endl;
cin >> accNum;
cout << "Enter pin#: "<<endl;;
getline(accPin);
//menu do while loop, unfinshed
do {
cout << "1. Check balance\n2.Make a deposit\n3.Logout\n";
cin >> option;
switch (option)
//check balance case
case 1:
// make a deposit case
case 2:
}
while (option !=3);
return 0;
}
Line 48 is where the array needs to be initialized, it contains the account number, the pin code, and the account balance (in that order). Can anyone point out the mistake I'm making? Thanks for the help in advance.
You need curly braces around the entire initializer list, and also around the initializer for each element.
Account account[]= {
{123, "abc123", 100.00},
{456, "def456", 50.00},
{789,"ghi789", 500.63}
};
I am trying to use a variable from the private class and both add and subtract from it at different times, first add 5 to it 5 times then subtract 5 from it 5 times and each time i have to display its value. Currently i have:
#include "stdafx.h"
#include <iomanip>
#include <iostream>
#include <string>
using namespace std;
class car {
private:
int year;
string make;
int speed;
public:
void StoreInfo(int y, string m, int s);
int getSpeed() { return speed; }
int accelerate() { speed += 5; }
int brake() { speed -= 5; }
};
void car::StoreInfo(int y, string m, int s) {
year = y;
make = m;
speed = s;
}
car fillFields() {
car Filler;
int year; // Local variables to hold user input
string make;
int speed = 0;
// Get the data from the user
cout << "Enter year: ";
cin >> year;
cout << "Enter make: ";
cin.get(); // Move past the '\n' left in the
// input buffer by the last input
getline(cin, make);
cout << "The current speed is " << speed << endl;
Filler.StoreInfo(year, make, speed);
return Filler;
}
int main() {
car numbers = fillFields();
car::accelerate();
return 0;
}
This code accepts the input but does not work after that i realize that the car::accelerate() line in the main is incorrect now but how would i use it correctly?
First accelerate and brake do not return any value so you can make them void
void accelerate() { speed += 5; }
void brake() { speed -= 5; }
accelerate is non-static member function and needs an object so you need to call it like:
numbers.accelerate();
And for example change your main function like this to accerelate once and then brake and see the speed:
int main() {
car numbers = fillFields();
numbers.accelerate(); // +5
cout << "The current speed is " << numbers.getSpeed() << endl;
numbers.brake(); // -5
cout << "The current speed is " << numbers.getSpeed() << endl;
return 0;
}
Outputs:
Enter year: Enter make: The current speed is 0
The current speed is 5
The current speed is 0
Demo
You can replace car::StoreInfo with a constructor, because it does what the constructors are meant for. And don't forget to initialize your variables.
numbers.accelerate();
You are not using any static data. You could rename numbers variable if you want.
Note - I have searched a lot on pointers and references for C++.
I don't seem to understand them in THIS particular scenario. Hence posting it here!
The following is CORRECT code. It is working. I wrote this for an online C++ practice problem. A part of the code was given to me initially.
I don't understand why an array of Person objects is being created in the main function with a *per[n] as shown below:
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
class Person {
string name;
int age;
public:
Person(){
name = "";
}
virtual void putdata() = 0;
virtual void getdata() = 0;
};
class Professor: public Person {
int publications, cur_id;
string name;
int age;
public:
static int professorCount;
Professor(){
name = "";
age = 0;
publications = 0;
cur_id = professorCount + 1;
professorCount++;
}
void getdata(){
cin >> name >> age >> publications;
}
void putdata(){
cout << name << " " << age << " " << publications << " " << cur_id << endl;
}
};
class Student: public Person {
int marks[6];
int cur_id;
string name;
int age;
public:
static int studentCount;
Student(){
name = "";
age = 0;
cur_id = studentCount + 1;
studentCount++;
}
void getdata(){
cin >> name >> age >> marks[0] >> marks[1] >> marks[2] >> marks[3] >> marks[4] >> marks[5];
}
void putdata(){
cout << name << " " << age << " " << marks[0] + marks[1] + marks[2] + marks[3] + marks[4] + marks[5] << " " << cur_id << endl;
}
};
int Professor::professorCount = 0;
int Student::studentCount = 0;
In this main function below, an array of Person objects is being created, but it is given a * in the beginning. How is it working?
int main(){
int n, val;
cin>>n; //The number of objects that is going to be created.
Person *per[n]; // THIS ONE RIGHT HERE! THIS ONE!
for(int i = 0;i < n;i++){
cin>>val;
if(val == 1){
// If val is 1 current object is of type Professor
per[i] = new Professor;
}
else per[i] = new Student; // Else the current object is of type Student
per[i]->getdata(); // Get the data from the user.
}
for(int i=0;i<n;i++)
per[i]->putdata(); // Print the required output for each object.
return 0;
}
I don't understand why an array of Person objects is being created in the main function with a *per[n] as shown below
The purpose of storing a pointer is to support virtual polymorphism (abstract classes like Person cannot be instantiated). A smart pointer serves that as well, but takes care about the correct dynamic memory management.
There's no need to use raw pointers or raw arrays in c++ at all. That code doesn't give a good example of "best practices".
At the main() function
Person *per[n]; // Note that VLA's aren't standard c++ syntax
should be replaced with
std::vector<std::unique_ptr<Person>> per(n);
and the loop accordingly
for(int i = 0;i < n;i++){
cin>>val;
if(val == 1){
// If val is 1 current object is of type Professor
per[i] = std::make_unique<Professor>();
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
}
// Else the current object is of type Student
else per[i] = std::make_unique<Student>();
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
per[i]->getdata(); // Get the data from the user.
}
Also
int marks[6];
should be replaced with
std::array<int,6> marks;
std::array is way more convenient and less error prone when passed as function parameter, etc.
You're creating an array of pointers to Person objects. That's how assignments like per[i] = new Professor; can work - new Professor returns a pointer to a Professor object, so you need an array of pointers to store that.
I want to create number of structure objects using input from user
for example:
I want to accept user value n and create n number of objects and pass these objects to a function where I initialize the variables to them.
#include <iostream>
#include<string>
#include "stdio.h"
using namespace std;
struct student
{
int roll_no;
char name[20];
};
void get_input(student p[],int n1)
{
for(int i=1;i<=n1;i++)
{
cout<<"Enter Roll Number ";
cin>>p[i].roll_no;
cout<<"\n Enter Name of the student: ";
cin>>p[i].name;
}
}
int main()
{
int n;
cout<<"How many student details would you want to enter: ";
cin>>n;
//Want to create number of object based on input n
student p[n];
get_input(student p[],n);
return 0;
}
There are a number of problems with your example.
The first problem is student p[n];. This is not strictly valid c++. Some compilers allow it as an extension. Without knowing which compiler you are using, and with what flags, I'll assume this is part of the problem. The typical solution for this problem is to use std::vector. An std::vector works in many ways like an array of variable size. std::vector<student> p(n); will create a vector named p containing n default constructed student objects.
The next problem is get_input(student p[],n);. It's unnecessary and incorrect to name the type when passing an argument. Just write get_input(p,n);. After all, you didn't specify that n is int when you called get_input. However, since p is an std::vector now, we need to add .data() to fetch a pointer to the actual data. It becomes get_input(p.data(), n);.
The final critical issue is the loop for (int i = 1; i <= n1; i++). Imagine n is 3. The values i will take are 1, 2 and 3. However, arrays are indexed starting at 0. If n is 3, you want to access the elements 0, 1 and 2. The correct loop is for (int i = 0; i < n1; i++).
These changes will allow your example to work but there are still many improvements that can be made.
#include <iostream>
#include <vector>
using namespace std;
struct student
{
int roll_no;
char name[20];
};
void get_input(student p[], int n1)
{
for (int i = 0; i < n1; i++)
{
cout << "Enter Roll Number ";
cin >> p[i].roll_no;
cout << "\n Enter Name of the student: ";
cin >> p[i].name;
}
}
int main()
{
int n;
cout << "How many student details would you want to enter: ";
cin >> n;
//Want to create number of object based on input n
std::vector<student> p(n);
get_input(p.data(), n);
return 0;
}
Consider using std::string instead of char name[20]. You won't have to guess how long a name might be, and you don't risk undefined behavior from having longer names.
struct student
{
int roll_no;
std::string name;
};
Consider passing p by reference, instead of using a pointer and size.
// Declaration / definition
void get_input(std::vector<student> & p)
// Usage
get_input(p);
Consider using a ranged based for loop instead of a regular for loop.
void get_input(std::vector<student> & p)
{
// for each student in p
for (student & s : p)
{
cout << "Enter Roll Number ";
cin >> s.roll_no;
cout << "\n Enter Name of the student: ";
cin >> s.name;
}
}
Use a vector of student: Here is some example code of how you can do it:
#include <iostream>
#include <string>
#include <vector>
#include "stdio.h"
using namespace std;
struct student
{ int roll_no;
char name[20];
};
void get_input(vector<student> & p1, int n1)
{
for (int i=0; i<n1; i++)
{
student s;
cout<<"Enter Roll Number: ";
cin>>s.roll_no;
cout<<"\n Enter Name of the student: ";
cin>>s.name;
p1.push_back(s);
}
}
int main()
{
int n;
cout<<"How many student details would you want to enter: ";
cin>>n;
//Want to create number of object based on input n
vector<student> p;
get_input(p, n);
return 0;
}
first of all am very new to C++. I am having some problem with my code. The program should able to get/read the value user entered and output it back. I tried get/set C++ methods, but am having some problem with getting and outputting the value in my main. The following is my code,
#include <iostream>
using namespace std;
class Store {
public:
//get and Set Price
void setPrice(int x){
price = x;
}
int getPrice(){
return price;
}
//Get and set % Marked Up
void setPercentageMarkedUp(int y){
markedUpPrice = y;
}
int getPercentageMarkedUp(){
return markedUpPrice;
}
//Get and set percentage Sales tax
void setPercentageSalesTax(int y){
percSalesTax = y;
}
int getPercentageSalesTax(){
return percSalesTax;
}
private:
int price;
int markedUpPrice;
int percSalesTax;
};
int main(){
int price;
Store obj;
cout << "enter the Original Price of the item: "<<endl;
obj.getPrice();
cout<<"the value is:"<<price<<endl;
return 0;
}
As am very new to both C++ and StackOverflow, please dont downgrade me for asking this simple question. I know its very basic. Will definitely appreciate those who helps. Thanks in advance.
Just need to update the main as follows
int main(){
Store obj;
int n_price;
cout << " Enter Original Price: " << endl;
cin >> n_price;
obj.setPrice(n_price);
cout << "Original Price: " << n_price<< endl;
return 0;
}
Thanks everyone. :)