I'm learning about C++ and when I was learning about Class, I ran into a problem. I try cout my element before entering the value, but the element already has a value. I can't understand why?
class cusTomer
{
char abc[30];
public:
void input();
void output();
};
void cusTomer::input(){
cout<<"abc: "; fflush(stdin); gets(abc);
}
void cusTomer::output(){
cout<<"abc: "<<abc<<endl;
}
class proDuct
{
char name[30];
public:
void input();
void output();
};
void proDuct::input()
{
cout<<"Name: "; fflush(stdin); gets(name);
}
void proDuct::output()
{
cout<<"Name: "<<name<<endl;
}
class bill
{
char date[30];
proDuct *y;
int n;
public:
void input();
void output();
};
void bill::input()
{
cout<<"Date: "; fflush(stdin); gets(date);
cout<<n<<endl; //16
cout<<"Input n: "; cin>>n;
cout<<n<<endl;
y=new proDuct[n];
for(int i=0;i<n;i++){
y[i].input();
}
}
void bill::output()
{
cout<<"Date: "<<date<<endl;
for(int i=0;i<n;i++){
y[i].output();
}
}
but the element already has a value.
An integer always has a value. There is no concept of valueless integer in C++.
If you haven't initialised an integer, then that value is indeterminate. If you read an indeterminate value, then the behaviour of the program is undefined. You should never read an indeterminate value.
P.S. gets is no longer part of C++, and it should never have been used.
my class is taught that fflush(stdin) to clear the buffer memory, then gets()/cin.getline() to input a string
Your class has been taught bad things.
Related
I am doing a university project and I am making a Library System.
It has a few restrictions I cannot use what we haven't been taught (so no vectors or std:: things).
Now, I have some classes made.
(1) Date
(2) Book
(3) Student
(4) Library //Haven't made it yet
Now, when a student/user issues a book their account number is being saved in "Book" class and so is the return_date.
Now, I wish to make a pointer or use this-> operator or something that will be in Student class but point to a Book class.
So, when Student wants to see which books they have currently issued will be displayed.
I am not sure how to do that.
Should I make a Library class, give it an array of "Book" class by composition and then make a member function in "Student/User" class and display it there?
I really want to use new/delete keyword, this, or pointers to do this. It's not compulsory but it will help me understand those concepts.
The following are my Book, Student and Date classes.
Date Class:
class Date
{
int Day; //1-31 based on month
int Month; //1-12
int Year; //any year
int checkDay(int );
int Late_Days;
public:
static const int Days_per_Month[13];
Date()
{
Day=0;
Month=0;
Year=0;
}
Date (int dy, int mn, int yr)
{
if (mn>0 && mn <=12)
Month=mn;
else
{
Month=1;
cout<<"Month "<<mn<<" invalid. Set to month 1"<<endl;
}
Year=yr;
Day=checkDay(dy);
}
void setDay(int d) {Day=d;}
void setMonth(int m) {Month=m;}
void setYear(int y) {Year=y;}
void setLateDay(int LD) {Late_Days=LD;}
int getDay() {return Day;}
int getMonth() {return Month;}
int getYear() {return Year;}
int getLateDay() {return Late_Days;}
void Print_Date()
{
cout<<getDay()<<"/"<<getMonth()<<"/"<<getYear()<<endl;
//cout<<Day<<"/"<<Month<<"/"<<Year<<endl;
}
void Update_Date()
{
cout<<"\nEnter Day: ";
cin>>Day;
cout<<"Enter Month: ";
cin>>Month;
cout<<"Year: ";
cin>>Year;
}
void increment_date(int num)
{
int day;
int month_new;
// Day=Day+num;
setDay(getDay()+num);
if( getDay()>Days_per_Month[getMonth()] )
{
day=getDay()-Days_per_Month[getMonth()];
setDay(day);
setMonth(getMonth()+1);
if(Days_per_Month[getMonth()]>12)
{
month_new=1;
setMonth(month_new);
setYear(getYear()+1);
}
}
Print_Date();
}
const int Date:: Days_per_Month[13]={0,31,28,31,30,31,30,31, 31, 30, 31, 30, 31};
int Date::checkDay(int testday) //returntype classname :: funcname (parameteres)
{
//static const int Days_per_Month[13]={0,31,28,31,30,31,30,31, 31, 30, 31, 30, 31};
if(testday > 0 && testday <= Days_per_Month[Month])
return testday;
if ( Month==2 && testday==29 && (Year%400==0 || (Year%4==0 && Year%100!=0)) ) //for leap year
return testday;
cout<<"Day "<<testday<<" invalid. Set to day 1."<<endl;
return 1;
}
Book Class
class Book
{
string Title;
string Author;
unsigned long int ISBN;
int Year_of_Publication;
int Library_Code;
string Category;
string Status;
unsigned int Account_Number; //if issued
int Copies_of_Book;
Date Return_Date;
public:
static int Copy_Number;
Book()
{
Title=" ";
Author=" ";
ISBN=0;
Year_of_Publication=0;
Library_Code=0;
Category=" ";
Status=" ";
Account_Number=0;
Copies_of_Book=0;
Return_Date.setDay(0);
Return_Date.setMonth(0);
Return_Date.setYear(0);
}
Book(string t, string a,unsigned long int isbn, int yop, int libcode, string c, string s, unsigned int an, int cob)
{
setTitle(t);
setAuthor(a);
setISBN(isbn);
setYOP(yop);
setLibraryCode(libcode);
setCategory(c);
setStatus(s);
setAccountNum(an);
setCopiesBook(cob);
}
void setTitle(string T) {Title=T;}
void setAuthor(string A) {Author=A;}
void setISBN(unsigned long int isbn){ISBN=isbn;}
void setYOP(int yop) {Year_of_Publication=yop;}
void setLibraryCode(int libcode) {Library_Code=libcode;}
void setCategory(string c) {Category=c;}
void setStatus(string s) {Status=s;}
void setAccountNum(unsigned int an) {Account_Number=an;}
void setCopiesBook(int cob) {Copies_of_Book=cob;}
void setCopyNumber(int cn) {Copy_Number=cn;}
string getTitle() {return Title;}
string getAuthor() {return Author;}
unsigned long int getISBN() {return ISBN;}
int getYOP() {return Year_of_Publication;}
int getLibraryCode() {return Library_Code;}
string getCategory() {return Category;}
string getStatus() {return Status;}
unsigned int getAccountNum() {return Account_Number;}
int getCopiesBook() {return Copies_of_Book;}
int getCopyNumber() {return Copy_Number;}
void Input_New_Book()
{
cout<<"\nEnter Title: ";
cin>>Title;
cout<<"Enter Author: ";
cin>>Author;
cout<<"Enter ISBN: ";
cin>>ISBN;
cout<<"Enter Year of Publication: ";
cin>>Year_of_Publication;
cout<<"Enter Library Code: ";
cin>>Library_Code;
cout<<"Enter Category: ";
cin>>Category;
cout<<"Enter Total Copies Number: ";
cin>>Copies_of_Book;
cout<<"Enter Status: ";
cin>>Status;
if(Status=="Issued")
{
cout<<"Enter Account Number: ";
cin>>Account_Number;
Return_Date.Update_Date();
}
}
void Display_Book_Info()
{
cout<<"\nTitle: "<<getTitle()<<endl;
cout<<"Author: "<<getAuthor()<<endl;
cout<<"ISBN: "<<getISBN()<<endl;
cout<<"Year of Publication: "<<getYOP()<<endl;
cout<<"Library Code: "<<getLibraryCode()<<endl;
cout<<"Category: "<<getCategory()<<endl;
cout<<"Total Copies: "<<getCopiesBook()<<endl;
cout<<"Status: "<<getStatus()<<endl;
if(getStatus()=="Issued")
{
cout<<"Account Number: "<<getAccountNum()<<endl;
cout<<"Return Date: ";
Return_Date.Print_Date();
}
}
void Update_Status()
{
unsigned int AN;
Display_Book_Info();
cout<<"Please enter the updated status of the book: ";
cin>>Status; //We cannot use string in an switch, so we are using if.
if (Status=="Lost")
{
cout<<"The book is lost."<<endl;
setAccountNum(0);
}
else if (Status=="Available")
{
cout<<"Book is available now to issue."<<endl;
setAccountNum(0); //This indicates it doesn't have nay account number.
}
else if(Status=="Issued")
{
cout<<"The book is in possession of someone."<<endl;
cout<<"Enter their account number:";
cin>>AN;
setAccountNum(AN);
}
else if (Status=="Order")
{
cout<<"The book is in process of being ordered."<<endl;
setAccountNum(0);
}
else
{
cout<<"Wrong entry!\nBook's Status is set to default. (Available)"<<endl;
Status="Available";
setAccountNum(0);
}
cout<<"Status updated successfully!"<<endl;
}
void Issue_Book(int day_num) //This day_num indicated number of days.
{
unsigned int an;
cout<<"Enter account number of User:";
cin>>an;
setAccountNum(an);
Return_Date.Update_Date();
cout<<"Book issued for "<<day_num<<" days."<<endl;
cout<<"Return Date: ";
Return_Date.Print_Date();
}
void ReIssue_Book(int day_num)
{
unsigned int an;
cout<<"Enter account number of User:";
cin>>an;
setAccountNum(an);
Return_Date.increment_date(day_num);
cout<<"Book issued for "<<day_num<<" more days."<<endl;
cout<<"Return Date: ";
Return_Date.Print_Date();
}
void Return_Book()
{
cout<<"Book returned from User: "<<getAccountNum()<<endl;
setAccountNum(0);
cout<<"Book returned successfully!"<<endl;
}
}; //end of class book
int Book::Copy_Number=0;
Student Class
class Student:public Book
{
string Name;
unsigned int Account_Number;
double Fine;
int Books_Issue;
public:
Student()
{
Name=" ";
Account_Number=0;
Fine=0;
Books_Issue=0;
}
void setName(string n) {Name=n;}
void setAccount_Number(unsigned int an) {Account_Number=an;}
void setFine(double f) {Fine=f;}
void setBooksIssue(int n) {Books_Issue=n;}
string getName() {return Name;}
unsigned int getAccount_Number() {return Account_Number;}
double getFine() {return Fine;}
int getBooksIssue() {return Books_Issue;}
void Input_Student_info()
{
cout<<"\nEnter Name: ";
cin>>Name;
cout<<"Enter Account Number: ";
cin>>Account_Number;
}
void Display_Student_info()
{
cout<<"Name: "<<getName()<<endl;
cout<<"Account Number: "<<getAccount_Number()<<endl;
cout<<"Total Fine: "<<getFine()<<endl;
cout<<"Books issued: "<<getBooksIssue()<<endl;
}
void Issue_a_book()
{
if(Books_Issue<=3)
{
Issue_Book(7); //This will issue a book and give it a 7 days return date time
Books_Issue++; //This will mean a book has been issued.
}
else
cout<<"Cannot issue book. You have reached your maximum limit.\nReturn a book in order to issue another."<<endl;
}
void Display_All_Books() //which are currently issued
{
for (int i=0 ; i<=getBooksIssue() ; i++)
{
}
}
};
Sorry for posting huge chunks of code. But some people say we should post the whole code, so this is why I posted all of it organized way.
The main question is:
How should I display issued books in a Student's class?
Should I make a Library class (as a parent class or child class, or use composition and arrays of Book class) first or at the very end?
Let me know what is the best way to do this.
Thank You so much.
It is better to have remove the user issue details from the book class...
Let the book class have only details about the book and methods to update and retrieve book details.
Add the user issue details into a new class which inherits the book class... This way is more modular and keeps the books as separate entities. Now you can make a linked list(as they are dynamic) or array of these classes, each holding a book and the issue and return dates for that particular student.
for example:
class books_issued{
public: book issued_book;
books_issued *new;
<put your issue data like:>
unsigned int Account_Number; //if issued
int Copies_of_Book;
Date Return_Date;
<and issue related methods:>
};
now declare an object of books_issued class in student class,
and write a method to add, remove and view books that have been issued by that particular student.
--- If you need any help with creating linked lists for this purpose, let me know I will be more than happy to help as I had done a very similar library management program for my project as well :-) ---
It has two issues
1). program is not taking input it exits without getting value of variable option.
2).Also my base and derived class are not initializing they are displaying garbage value.
Here is complete code.
#include<iostream>
using namespace std;
class BeverageItem
{
protected:
string name;
double price;
public:
void set_name(string n);
string get_name();
void set_price(double pr);
double get_price();
};
void BeverageItem::set_name(string n)
{
name=n;
}
string BeverageItem::get_name()
{
return(name);
}
void BeverageItem::set_price(double pr)
{
price=pr;
}
double BeverageItem::get_price()
{
return(price);
}
class HotBeverage:public BeverageItem
{
private:
int tea_bags;
int whiteners;
public:
//HotBeverage(int bg,int wht);
void set_teabags(int t_bags);
int get_teabags();
int getwhiteners();
void set_whiteners(int wht);
double basePrice();
double computeTax();
double totalCost();
void print();
};
double HotBeverage::computeTax()
{
return (0.16*price);
}
double HotBeverage::totalCost()
{
return(price+computeTax());
}
double HotBeverage::basePrice()
{
double pr;
if((tea_bags==1)&& (whiteners==1))
{
pr=20;
}
else if((tea_bags>1)&& (whiteners>1))
{
tea_bags=tea_bags-1;
pr=20+(5*tea_bags);
}
set_price(pr);
return(pr);
}
void HotBeverage::set_teabags(int t_bags)
{
tea_bags=t_bags;
}
int HotBeverage::get_teabags()
{
return(tea_bags);
}
int HotBeverage::HotBeverage::getwhiteners()
{
return(whiteners);
}
void HotBeverage::set_whiteners(int wht)
{
whiteners=wht;
}
void HotBeverage::print()
{
cout<<"Name: "<<name<<endl;
cout<<"Tax:"<<computeTax()<<endl;
cout<<"Total Cost: "<<totalCost()<<endl;
}
class ColdBeverage:public BeverageItem
{
private:
int drinkSize;
public:
//ColdBeverage(int drinkSize);
void setDrinkSsize(int sz);
int getDrinkSize();
double basePrice();
double computeTax();
double totalCost();
void print();
};
void ColdBeverage::print()
{
cout<<"Name: "<<name<<endl;
cout<<"Tax:"<<computeTax()<<endl;
cout<<"Total Cost: "<<totalCost()<<endl;
}
void ColdBeverage::setDrinkSsize(int sz)
{
drinkSize=sz;
}
int ColdBeverage::getDrinkSize()
{
return(drinkSize);
}
double ColdBeverage::computeTax()
{
return (0.16*price);
}
double ColdBeverage::totalCost()
{
return(price+computeTax());
}
double ColdBeverage::basePrice()
{
double pr;
double regularPr=30;
switch(drinkSize)
{
case 1: //regular,
pr=regularPr;
break;
case 2: //large.
price=1.5*regularPr;
break;
case 3: //extra large.
price=2*regularPr;
break;
}
set_price(pr);
return(pr);
}
int main()
{
string name;
int option;
cout<<"Enter The Beverage Name=";
cin>>name;
cout<<"1. For Hot Beverage\n\n";
cout<<"2. For Cold Beverage\n\n";
cout<<"Select Your Choice(1,2)=";
cin>>option;
BeverageItem bi;
bi.set_name(name);
**//some other code here.**
return 0;
}
1) I don't really see a problem with the compiler i tried with
http://cpp.sh/4p5mw
2) POD's in member variables are not default initialised.
https://stackoverflow.com/a/15212447/4669663
Here was the issue
cin>>name;
cin stops when whitespaces are entered in a string so I would have to use
getline(cin,name);
Second issue was because i was not calling the basePrice() before print()
thanks to everyone
I want float variable 'avg' to be returned and then in the main pass it to 'void batsman::display(float a)' using a parameter. then display the average marks in display method. this method gives me 2 errors. any other way?
#include<iostream.h>
class batsman
{
int marks[5];
char name[15],country[15];
public:
void input();
float cal();
void display();
};
void batsman::input()
{
int i;
cout<<"Enter player name: ";
cin>>name;
cout<<"Enter player country: ";
cin>>country;
cout<<"Enter player marks"<<"\n";
for(i=0;i<5;i++)
{
cout<<"Mark "<<i+1<<": ";
cin>>marks[i];
}
}
float batsman::cal()
{
int i;
int tot=0;
float avg;
for(i=0;i<5;i++)
{
tot=tot+marks[i];
}
avg=(float)tot/5;
return avg;
}
void batsman::display(float a)
{
float avg1;
avg1=a;
cout<<"Player name: "<<name<<"\n";
cout<<"Player country: "<<country<<"\n";
cout<<"Average: "<<avg1<<"\n";
}
int main()
{
batsman b1;
b1.input();
b1.cal();
b1.display(b1.batsman::cal());
//cout<<"Average: "<<b1.batsman::cal()<<"\n";
}
The code has several errors.
iostream.h should be iostream
using namespace std; // add this at top so that cout is found
display() should be display(float a) in the class declaration.
After those changes the code ran as expected.
Change display's definition in your class to display(float a), and prepend std:: to cout and cin. As a recommendation, don't use iostream.h, use iostream.
here is my code. wriiten for to to find armstrong, factorial etc. now i want readNo method private what should i do..?
#include<iostream.h>
#include<stdio.h>
#include<conio.h>
class Num_Demo
{
public:
int num;
void readNo(int no)
{
num=no;
}
int Factorial (int a)
{
if(a!=0)
{
int f=1;
for (int i=1;i<=a;i++)
{
f=f*i;
}
return f;
}
else
{
return 0;
}
}
int Reverse(int b)
{
int rev=0,rem;
while(b!=0)
{
rem=b%10;
rev=(rev*10)+rem;
b=b/10;
}
return rev;
}
void Palindrome (int c)
{
int num;
int rev=0,rem;
num=c;
while(c!=0)
{
rem=c%10;
rev=(rev*10)+rem;
c=c/10;
}
if(num==rev)
{
cout<<" Number Is Palindrome";
}
else
cout<<" Number is Not Plaindrome";
}
void Armstrong (int d)
{
int sum=0,n1,copy;
copy=d;
while(d!=0)
{
n1=d%10;
sum=sum+n1*n1*n1;
d=d/10;
}
if(sum==copy)
{
cout<<" Number Is Armstrong";
}
else
cout<<" Number is Not Armstrong";
}
};
int main()
{ clrscr();
Num_Demo nd1,nd2,nd3,nd4;
int n1,n2,n3,n4;
cout<<"\n\nEnter The Number To Find Factorial\t";
cin>>n1;
nd1.readNo(n1);
cout<<" The Factorial Is\t"<<nd1.Factorial(n1);
cout<<"\n\nEnter The Number To Find Reverse Number\t";
cin>>n2;
nd2.readNo(n2);
cout<<" The Reverse Is\t"<<nd2.Reverse(n2);
cout<<"\n\nEnter The Number To Find Palindrome\t";
cin>>n3;
nd3.readNo(n3);
nd3.Palindrome(n3);
cout<<"\n\nEnter The Number To Find Armstrong\t";
cin>>n4;
nd4.readNo(n4);
nd3.Armstrong(n4);
getch();
return 0;
}
now i want to make readNo method private. what should i do..? whent i place readNo outside public error "readNo not accessible" pop up. please help me.
You don't use a private function in main function. It's unacceptably.
You put function under private: tag in class definition, but then you can't call it outside from your class, soo then you need public function which will call private function in class.
Im new to classes and i have to write my own functions and variables in a class that stores rover information when it is entered and for some reason whenever I write my functions and try to call them in main they are not working. I have provided my code and Im wondering if someone can help me explain how to get the rovers data to be stored for each rover r1-r5. Thank you.
class Rover{
private:
string name;
int xpos;
int ypos;
string direction; //Use Cardinal Directions (N,S,E,W)
int speed; //(0-5 m/sec)
public:
//Constructors
//defaultRover();
//Rover();
//Get functions
string getName();
int getXpos();
int getYpos();
string getDirect();
int getSpeed();
void getRoverData();
//Set functions
string setName();
void setXpos();
void setYpos();
void setDirect();
void setSpeed();
};
//Constructor function
/*Rover::defaultRover()
{
xpos=0;
ypos=0;
direction="N";
speed=0;
}
*/
/*
Rover::Rover()
{
cout<<"Please enter the starting X-position: ";
cin>>xpos;
cout<<"Please enter the starting Y-position: ";
cin>>ypos;
cout<<"Please enter the starting direction (N,S,E,W): ";
cin>>direction;
cout<<"Please enter the starting speed (0-5): ";
cin>>speed;
cout<<endl;
}
*/
//Getter functions
string Rover::getName()
{
return name;
}
int Rover::getXpos()
{
return xpos;
}
int Rover::getYpos()
{
return ypos;
}
string Rover::getDirect()
{
return direction;
}
int Rover::getSpeed()
{
return speed;
}
void Rover::getRoverData()
{
cout<<name;
cout<<xpos;
cout<<ypos;
cout<<direction;
cout<<speed;
}
//Setter functions
string Rover::setName()
{
cout<<"Please enter the Rover name ";
cin>>name;
}
void Rover::setXpos()
{
cout<<"Please enter the X-position of the Rover ";
cin>>xpos;
}
void Rover::setYpos()
{
cout<<"Please enter the Y-position of the Rover ";
cin>>ypos;
}
void Rover::setDirect()
{
cout<<"Please enter the direction of the Rover (N,S,E,W) ";
cin>>direction;
}
void Rover::setSpeed()
{
cout<<"Please enter the speed of the Rover (0-5) ";
cin>>speed;
}
int main(int argc, char** argv)
{
Rover r1, r2, r3, r4, r5;
r1.setName();
r1.getName();
return 0;
}
As a general rule...
getters and setters should not communicate with stdin or stdout
getters should return what they're getting
setters should assign the member to what is being passed in
Let's make a pretend class Foo:
class Foo {
public:
// setters
void set_bar(int bar) { bar_ = bar; }
void set_baz(std::string baz) { baz_ = baz; }
void set_boo(double boo) { boo_ = boo; }
// getters
int get_bar() const { return bar_; }
std::string get_baz() const { return baz_; }
double get_boo() const { return boo_; }
private:
int bar_;
std::string baz_;
double boo_;
};
The way this should be used is something like this:
Foo foo;
int bar;
std::cout << "Please enter bar: " << std::endl;
std::cin >> bar;
foo.set_bar(bar);
std::cout << "foo's bar is " << foo.get_bar() << std::endl;
You need to change a lot of code, but I hope this helped.