How to fix interrupted console when using inheritance - c++

I'm a student and I'm just learning inheritance, so i do a simple example. But when i excuted my code, it just did the first statements and stopped. What's my fault? I have so experience to ask for debugging.
class people
{
private:
string name;
protected:
string phone;
public:
string age;
string setName(string name)
{
this-> name = name;
}
string getName()
{
return name;
}
};
class student: public people
{
public:
string setPhone(string phone)
{
this-> phone = phone;
}
string getPhone()
{
return phone;
}
};
int main()
{
student ict;
string name, phone;
cout<<"\nEnter name: "; getline(cin,name);
ict.setName(name);
cout<<"\nEnter phone: "; getline(cin,phone);
ict.setPhone(phone);
cout<<"\nEnter age: "; cin>>ict.age;
cout<<"\n==============================\nYour info: ";
cout<<"\nName:"<<ict.getName();
cout<<"\nPhone: "<<ict.getPhone();
cout<<"\nAge: "<<ict.age;
return 0;
}

As far as I can see your issue is that your setName() and setPhone() functions have a string return type, however they don't change anything. In general you should have these as a void return type.
When I made this minor change the code compiled and ran perfectly fine for me.
On that sidenote, your method/reasoning to have the setPhone() function in the student class is a bit odd, especially since the variable of phone is itself in your people class instead.

Related

How to initialize object of a class if the values are stored in a .txt file in C++

How to initialize an object of a class if the values are stored in a .txt file in C++
I'm Making A Data Management System Which has 3 Options:-
Add a new student.
View a student's information.
Delete a student.
And the code looks something like this
#include <iostream>
using namespace std;
//Struct Containing The Service Numbers
struct Service
{
string Add="1";
string View="2";
string Delete="3";
};
//The Main Student Class
class Student
{
public:
//Bio Of Student
string Name;
int Age;
string Gender;
int Class;
//Constructer Insitializing The Bio Variable
Student(string Name,string Gender,int Age,int Class)
{
this->Name=Name;
this->Gender=Gender;
this->Age=Age;
this->Class=Class;
}
};
int main()
{
std::cout<<"•Add A Student [PRESS 1]\n•View Student's Information [PRESS 2]\n•Delete A Student [PRESS 3]"<<endl;
//Goto Statement If Input Is Incorrect
Err:
cout<<"Which Service Do You Want To Access :";
int Age;
int Class;
string Serv;
cin>>Serv;
Service ser;
//Bunch Of If Statement
if(Serv!=ser.Add && Serv!=ser.Delete&& Serv!=ser.View)
{
cout<<endl<<"\nInvalid Input Try Again!"<<endl<<endl;
goto Err;
}
else
{
if(Serv==ser.Add)
{
cout<<endl<<"Name Of The Student :";
string Name;
cin>>Name;
ReGen:
cout<<endl<<"Gender Of The Student :";
string Gender;
cin>>Gender;
transform(Gender.begin(), Gender.end(), Gender.begin(), ::tolower);
if(Gender!="male" && Gender!="female")
{
goto ReGen;
}
else
{
cout<<"\nAge Of The Student :";
int Age;
cin>>Age;
Res:
if(!cin || Age<0 || Age>20)
{
cout<<endl<<"Age Must Be String & Must Be Greater Than 5 And Lesser Than 20"<<endl;
cout<<"\nAge Of The Student :";
cin>>Age;
if(!cin || Age<0 || Age>20)
{
goto Res;
}
else
{
cout<<endl<<"Class Of The Student :";
int Class;
cin>>Class;
Res1:
if(!cin || Class<=0 || Class>12)
{
cout<<endl<<"Class Of Student Must Be String & Must Be Greater Than 0 And Lesser Than 12"<<endl;
cout<<"\nAge Of The Student :";
cin>>Age;
if(!cin || Class<1 || Age>12)
{
goto Res1;
}
}
}
}
Student ID1(Name,Gender,Age,Class);
}
}
}
}
What this code does is:-
It takes the input of all necessary things like Name, Age, Gender, Class.
So what I want to do is to create the instance of the class using the name of the student.
Explore data structures such as sets and maps in Cpp.
Apart from a thousand possible solutions of this problem, here is one:
class Student{
string name = "no_student";
/* appropriate members */
};
map<string, Student> m; // mapping from string-name to Student-objects
\\ ADDING A STUDENT:
m[name] = Student(name, age, gender, class); \\ Appropriately define a constructor.
\\ Finding a student through name:
Student x = m[name];
if(m[name] == "no_student"){
/* NO STUDENT FOUND CASE*/
}
else{
/* ACCESS STUDENT IN X */
}
\\ Removing an element:
/* figure out on your own */
The answer to your question is maps explore it now (:

How to let a user add to and remove from "slots" in an array?

I have a project in my C++ class - we're supposed to make a "simple student management system" comprised of a class for the student attribute variables, and a main function with a branch statement that lets the user input names and IDs for the students. I know that I need to use an array to make "slots" for the students, and that my branch statements need to let the user input values into those slots, but I'm not exactly sure how to do it. Here is the code that I have so far.
#include <string>
#include <iostream>
#include <utility>
using std::string;
using std::cin;
using std::cout;
using std::endl;
struct Student {
private:
int id;
string name;
int birthday;
public:
Student()
{
id = 0;
birthday = 0;
}
Student(int id, string name, int birthday)
{
//set your parameters to the class variables
this->id = id;
this->name = name;
this->birthday = birthday;
}
void setID(int id)
{
this->id = id;
}
int getID() {
return id;
}
void setName(string name)
{
this->name = name;
}
string getName()
{
return name;
}
void setBirthday(int birthday)
{
this->birthday = birthday;
}
int getBirthday()
{
return birthday;
}
void output() {
cout << id << name << birthday << endl;
}
};
int main() {
Student arr[50];
cout << "Student Management System" << endl;
cout << "Press 'a' to add a student" << endl;
char a = 1;
int y = 1;
while (a == 'a') {
switch (y)
{
cout << "Input Student ID:";
cin >> id;
}
}
}
What I'm focusing on most is the fourth line from the bottom. I was told that I need to use my setters, so I said that I want what my user inputs to be treated as the value of the ID variable that I set in the class. However, when I wrote this out, I was given an error. Could someone tell me what the issue is?
You should try to get your switch statement working correctly. To use classes setters, you can store the user input to a temporary variable then from your one student you can call the member function. i.e. in your case:
arr[index].setID(tempInputVariable);
There is no id in your main function or as a global variable.
I suggest you overload operator >> to have your structure extract its members from the data stream:
struct Student
{
//...
public:
friend std::istream& operator>>(std::istream& input, Student& s);
};
std::istream& operator>>(std::istream& input, Student& s)
{
input >> s.id;
input >> s.name;
input >> s.birthday;
return input;
}
Although the above code doesn't use setters, it is the preferred method for inputting data.
The overload can be modified to use setters (kind of overkill):
std::istream& operator>>(std::istream& input, Student& s)
{
int id;
input >> id;
s.setID(id);
std::string name;
input >> name;
s.setName(name);
int birthday;
input >> birthday;
s.setBirthday(birthday);
return input;
}
If you don't like the overload, you can perform the steps in your main function:
//...
Student new_student;
//...
{
int student_id;
std::cout << "Input Student ID:";
std::cin >> student_id;
new_student.setID(student_id);
std::string student_name;
std::cout << "Input Student Name: ";
std::cin >> student_name;
new_student.setName(student_name);
int student_birthday;
std::cout << "Input Student Birthday: ";
std::cin >> student_birthday;
new_student.setBirthday(student_birthday);
}
Edit 1: The Database
You'll probably need to store or remember the students. This is easy using the first method above:
std::vector<Student> database;
Student s;
std::cout << "Enter student information (ID, Name and birthday, separated by spaces:\n";
std::cin >> s;
// Append to the database
database.push_back(s);
If you haven't learned std::vector you can try an array:
const size_t MAXIMUM_STUDENTS = 16;
Student database[MAXIMUM_STUDENTS];
size_t database_index = 0;
//...
Student s;
std::cout << "Enter student information (ID, Name and birthday, separated by spaces:\n";
std::cin >> s;
// Append to database
database[database_index] = s;
++database_index;

Can't convert string to int in return. No string variable declared whatsoever in int returning function getsocial()

#include<iostream>
#include<string>
using namespace std;
/*this program takes a bank customer's info with the use of a class*/
//class definition
class BankCustomer
{
public:
BankCustomer(); //constructor for BankCustomer class
void fullname(string, string);
string firstname();
string lastname();
bool setsocial(int s); //accept a arg. of int type
int getsocial();
private:
string fname, lname, SSNlength; //can't be changed by client; sensitive info should be made private
};
//class implementation
BankCustomer::BankCustomer(){}
void BankCustomer::fullname(string f, string l)
{
fname=f;
lname=l;
}
string BankCustomer::firstname()
{
return fname;
}
string BankCustomer::lastname()
{
return lname;
}
bool BankCustomer::setsocial(int s)//function verifies that entered SSN is 9 digits long by counting # of digits of entered SSN
{
int count, SSNlength;
while(s != 0)
{
s /=10;
++count;
if(count == 9)
{
cout <<"\nValid SSN Entered!" << endl;
SSNlength=s;
return true;
}
}
}
int BankCustomer::getsocial()
{
return SSNlength;
}
//client program
int main()
{
BankCustomer customer; //customer declared as object of BankCust class
string firstname, lastname;
int ssn, s;
//data assignment
cout <<"\n Enter First Name\n" << endl;
cin >> firstname;
cout<<"\n Enter Last Name\n"<< endl;
cin >> lastname;
customer.fullname(firstname,lastname);
do
{
cout<<"\nEnter 9-Digit SSN"<< endl;
cin >> ssn;
customer.setsocial(ssn);
}
while(!customer.setsocial(ssn)); //function will repeat as long as entered user ssn forces setsocial() to evaluate it as false
//data ouput
cout <<"\nFirst Name: "<<customer.firstname()<<"\n"<< endl;
cout <<"\nLast Name: "<<customer.lastname()<<"\n"<< endl;
cout <<"\n SSN is: "<<customer.getsocial()<<"\n" << endl;
}
The error is targeting BankCustomer::getsocial(). The variable SSNlength is declared as an int type and getsocial() has a return type of int. I don't see anywhere in my code where I intend to convert SSNlength to a string. Is it how I'm passing and handling data with the setsocial() function?
That is wrong:
int BankCustomer::getsocial()
{
return SSNlength;
}
since SSNlength is a member variable of the class BankCustomer of type string, visible from BankCustomer::getsocial, even if not declared in the method. That how C++ works.
So the compiler complains that it cannot convert a string to an int (what you want to return).
this is where you declare it:
private:
string fname, lname, SSNlength; //can't be changed by client; sensitive info should be made private
Given the name of the variable, I suspect that you wanted to write:
private:
string fname, lname;
int SSNlength; //can't be changed by client; sensitive info should be made private
be careful, there's an auto variable called the same way in another method.
I suggest a naming rule for members to avoid all that. Example: prefix all members with m_:
private:
string m_fname, m_lname
int m_SSNlength; //can't be changed by client; sensitive info should be made private

Updating objects with getline doesn't seem to work

I'm having odd behavior when creating and using a class.
I create multiple instances of that class, sequentially - and then I create a few temp variables to prompt the user to enter some data, then i use basic mututaor functions and pass the data to the parts of the object. I do this for the first item, then the second, etc.
What happens when the declarations of those personalData elements are sequential then for some reason the cin/getline statements skip over some and i can't enter all the data correctly. When i spread them out between statements have one object created then the input from the user then updates, then the next object it works better but still not in 100% of the cases. Lastly i found that creating different variables for inputting data - my temp variables also resolves the problem but that seems strange to have to create a dozen variables when i should be able to input data/update existing ones?
class personalData
{
private:
string name;
string address;
int phone;
int age;
public:
void setname(string);
void setadress(string);
void setphone(int);
void setage(int);
string getname()const;
string getadress()const;
int getage()const;
int getphone()const;
};
void personalData::setname(string n)
{ name=n; }
void personalData::setadress(string a)
{ address=a; }
void personalData::setphone(int p)
{ phone=p;}
void personalData::setage(int ag)
{age=ag;}
string personalData::getname()const
{return name;}
string personalData::getadress()const
{return address;}
int personalData::getage()const
{return age;}
int personalData ::getphone()const
{return phone;}
int main()
{
personalData my;
personalData friendd;
personalData family;
string n;
string a;
int p;
int g;
cout<<"enter your name";
getline(cin,n);
cout<<"enter your address:";
getline(cin,a);
cout<<"enter your phone:";
cin>>p;
cout<<"enter your age";
cin>>g;
my.setname(n);
my.setadress(a);
my.setphone(p);
my.setage(g);
cout<<"enter your friend's name";
getline(cin,n);
cout<<"enter your friend's address:";
getline(cin,a);
cout<<"enter your friend's phone:";
cin>>p;
cout<<"enter your friend's age";
cin>>g;
friendd.setname(n);
friendd.setadress(a);
friendd.setphone(p);
friendd.setage(g);
cout<<"enter your family member's name";
getline(cin,n);
cout<<"enter your family member's address:";
getline(cin,a);
cout<<"enter your family member's phone:";
cin>>p;
cout<<"enter your family member's age";
cin>>g;
family.setname(n);
family.setadress(a);
family.setphone(p);
family.setage(g);
cout<<"my name"<<my.getname()<<endl;
cout<<"my address"<<my.getadress()<<endl;
cout<<"my phone"<<my.getphone()<<endl;
cout<<"my age"<<my.getage()<<endl;
// more cout statements with objects.getData ...
return 0;
}
Sorry for the long piece of code, I'm stuck and can't figure out what the issues are.
Thanks.

Assigning a string from standard input to a class member variable

I've been stuck in this and couldn't find a way out of it searching on the internet. This chunk of code supposed to prompt a user for a 3 different string and assign them to member variables of a class.
void Book::setBookProperty()
{
string name;
string publisher;
string category;
int published_year;
double price;
// Prompt for book infromation
cout << "Name of the Book: ";
getline(cin, name, '\n');
this->name = name;
cout << "Publisher: ";
getline(cin, publisher, '\n');
this->publisher = publisher;
cout << "Category: ";
getline(cin, category, '\n');
this->category = category;
cout << "Published year: ";
cin >> published_year;
this->published_year = published_year;
cout << "Price:";
cin >> price;
this->price = price;
}
name, publisher, category, published_year and price are all the private member of the class Book. Assigning those from standard input I'm getting memory access violation!!! which I don understand where am I going wrong.
Any help?
And this is how this function is being invoked from another class called BookStore:
void BookStore::addBook(int No)
{
book[No].setBookProperty();
}
Your book array in BookStore has a length of zero. So you can't fit any books in there. When you call addBook(1), it tries to access book[1] which is past the end of the array, so it is writing to memory it doesn't own.
A quick fix is to set an upper limit to the number of books:
book = new Book[10]; // book store with only 10 books allowed.
A better fix is to store the books in a collection such as std::vector. You can then check if the vector has enough space for book you want to add and add extra room if you need.
vector<Book> book;
void BookStore::addBook(int No)
{
if (book.size() <= No)
book.resize(No+1);
book[No].setBookProperty();
}
Note that both vectors and arrays are zero based, which is why you need to resize to No+1
This is how BookStore is defined and an object of Book is being instantiated within it.
class BookStore
{
public:
BookStore(string name)
{
storeName = name;
book = new Book[];
}
Book getBook(int);
void addBook(int); // prompts for information
private:
string storeName;
Book *book;
};
And this is how this whole is being called from the main function:
int main()
{
BookStore Amazon("amazon");
Amazon.addBook(1);
}