I need to create a class of Students where I need to store their name, surname and subjects that they have in uni. How do I need to assign different subjects to different students? User should input it from console. What my class and input should look like? Heres is the code I have so far For example: there are two students Mark Jacobs and John Johny. Mark has 3 subjects: Math, Physics, Geography and John only has 2 Math and Economy.
#include <iostream>
using namespace std;
class Student{
private:
string name;
string surname;
int courseNo;
string subjects[100];
public:
Student(string name = "empty", string surname = "empty")
{
this->name = name + surname;
}
~Student(){
}
void setFullName(string name, string surname){
this->name = name;
this->surname = surname;
}
string getFullName(){
return name + " " + surname;
}
void setSubject(string subjects[100]){
this->subjects[90] = subjects[90];
}
string getSubject(){
return subjects[90];
}
string toString() const
{
return "Studentas: " + this->name;
}
};
int main() {
int number_of_students;
int number_of_subjects = 0;
int choice;
string subjects[90];
string name;
string surname;
cout << "Enter number of students: ";
cin >> number_of_students;
Student Studentas[number_of_students];
cout << "Enter " << number_of_students << " students names and surnames: " << endl;
for (int i = 0; i < number_of_students; i++) {
cin >> name >> surname;
Studentas[i].setFullName(name, surname);
}
for (int i = 0; i < number_of_students; i++) {
cout << i+1 << " Student: " << Studentas[i].getFullName() << endl;
}
cout << "Choose which students subjects you want to enter: ";
cin >> choice;
if(choice == 1){
cout << "Enter " << Studentas[choice-1].getFullName() << " number of subjects: ";
cin >> number_of_subjects;
for (int i = 0; i < number_of_subjects; i++) {
cin >> subjects[i];
Studentas[choice-1].setSubject(subjects);
}
cout << "Studying subjects are: " << endl;
for(int i = 0; i < number_of_subjects; i++){
cout << Studentas[choice-1].getSubject() << endl;
}
}
return 0;
}
I have taken your code changed a little bit, I hope this is what you are looking for
Code:
#include <iostream>
#include <vector>
using namespace std;
class Student {
private:
string name_;
string surname_;
int courseNo_;
std::vector<string> subject_list_;
public:
Student(string name = "empty", string surname = "empty")
{
name_ = name + surname;
}
void setFullName(string name, string surname) {
name_ = name;
surname_ = surname;
}
string getFullName() {
return name_ + " " + surname_;
}
void setSubject(string subject) {
subject_list_.push_back(subject);
}
const std::vector<string>& getSubjects() {
return subject_list_;
}
string toString() const
{
return "Student as: " + name_;
}
};
int main() {
std::vector<Student> student_list;
int number_of_students;
int number_of_subjects = 0;
int choice;
string subject;
string name;
string surname;
cout << "Enter number of students: ";
cin >> number_of_students;
cout << "Enter " << number_of_students << " students names and surnames: " << endl;
for (int i = 0; i < number_of_students; i++) {
cin >> name >> surname;
student_list.push_back(Student(name, surname));
}
int i = 1;
for (auto student : student_list) {
cout << i++ << " Student: " << student.getFullName() << endl;
}
cout << "Choose which students subjects you want to enter: ";
cin >> choice;
if (choice <= number_of_students) {
choice -= 1;
cout << "Enter " << student_list[choice].getFullName() << " number of subjects: ";
cin >> number_of_subjects;
for (int i = 0; i < number_of_subjects; i++) {
cin >> subject;
student_list[choice].setSubject(subject);
}
cout << "Studying subjects are: " << endl;
const auto& subject_list = student_list[choice].getSubjects();
for (auto& subject : subject_list){
cout << subject << endl;
}
}
return 0;
}
Related
For one of my options, I had to add a row of data to my struct array, I was able to update the array but it does not update the actual array. So I am trying to update my struct array by passing it as a reference. I placed the '&' sign before the name of the variable, but all my indexes within the function errored.. I'm still a newbie to programing and I'm not "allowed " to use any vectors according to my Professor. . I looked online and placed the '&' on the function name as well as on the prototype. I also changed it from void to the "data type" to return the updated array, but no luck... I hope this comes out clear....
#include<iostream>
#include<iomanip>
#include<fstream>
using namespace std;
struct Data {
string first_name;
string last_name;
int employee_id;
string phone_number;
};
void readFile( ifstream& , string, Data [],int&);
void getEmployeeDetail(Data [], int&);
void getEmployeeLast(Data [], int&);
Data getAddEmployee(Data &, int&);
void getRemoveEmployee();
void getManagerOnly();
void getStaffOnly();
const int SIZE = 15;
Data employee[SIZE];
int main() {
ifstream inputFile;
ofstream outputFile;
int count = 0;
int selection;
const int EMPLOYEE_DETAIL = 1,
EMPLOYEE_LAST = 2,
ADD_EMPLOYEE = 3,
REMOVE_EMPLOYEE = 4,
MANAGER_ONLY = 5,
STAFF_ONLY = 6,
QUIT = 7;
readFile( inputFile ,"employeeData.txt", employee,count);
do {
cout << "\t Please select your option.\n"
<< "1. List all employee details\n"
<< "2. List employee by last name\n"
<< "3. Add a new employee\n"
<< "4. Remove an employee\n"
<< "5. Show all managers only\n"
<< "6. Show all staff only\n"
<< "7. Quit\n"
<< "Please enter your selection.\n" << endl;
cin >> selection;
while (selection < EMPLOYEE_DETAIL || selection > QUIT) {
cout << " Pleasse enter a valid selection.\n";
cin >> selection;
}
switch (selection) {
case EMPLOYEE_DETAIL:
getEmployeeDetail(employee,count);
break;
case EMPLOYEE_LAST:
getEmployeeLast(employee, count);
break;
case ADD_EMPLOYEE:
getAddEmployee(employee, count);
break;
case REMOVE_EMPLOYEE:
getRemoveEmployee();
break;
case MANAGER_ONLY:
getManagerOnly();
break;
case STAFF_ONLY:
getStaffOnly();
break;
case QUIT:
cout << "Program ending\n";
break;
}
} while (selection != QUIT);
system("pause");
return(0);
}
void readFile(ifstream& inputFile, string data, Data employee[],int &count) {
inputFile.open(data);
if (!inputFile) {
cout << " Error in opening file\n";
exit(1);
}
else {
while (!inputFile.eof()) {
inputFile >> employee[count].first_name;
inputFile >> employee[count].last_name >> employee[count].employee_id >> employee[count].phone_number;
count++;
}
inputFile.close();
}
return;
};
void readFile(ifstream& inputFile, string data, Data employee[],int &count) {
inputFile.open(data);
if (!inputFile) {
cout << " Error in opening file\n";
exit(1);
}
else {
while (!inputFile.eof()) {
inputFile >> employee[count].first_name;
inputFile >> employee[count].last_name >> employee[count].employee_id >> employee[count].phone_number;
count++;
}
inputFile.close();
}
return;
};
void getEmployeeDetail( Data employee[], int& count) {
cout << "Firt Name" << "\t" << "Last Name " << "\t" << "Employee ID " << "\t" << "Phone Number \n";
cout << "--------------------------------------------------------------------------\n";
for(int i =0; i < count; i++)
cout <<employee[i].first_name<<"\t\t"<<employee[i].last_name<<"\t\t"<<employee[i].employee_id<<"\t\t"<<employee[i].phone_number<< "\n ";
cout << endl;
}
void getEmployeeLast(Data employee[], int& count) {
string searchName;
cout << "Please enter the last name of the employee you want to search for.\n";
cin >> searchName;
/*
for (int i = 0; i < count; i++)
if (searchName ==employee[i].last_name) {
cout << employee[i].last_name;
}
*/
string matchString = searchName;
for (int i = 0; i < count; i++) {
if (employee[i].last_name.find(matchString, 0) != std::string::npos) {
cout << employee[i].last_name << endl;
}
else {
cout << "No employee was located with that name.\n";
exit(1);
}
}
}
Data getAddEmployee(Data &employee, int& count) {
string firstName, lastName, phoneNumber;
int employeeID, size;
for (int i = 0; i < count; i++)
cout << employee[i].first_name << "\t\t\t" << employee[i].last_name << "\t\t" << employee[i].employee_id << "\t\t" << employee[i].phone_number << "\n ";
cout << endl;
cout << count <<"\n";
size = count + 1;
cout << size << "\n";
cout << "Please enter the new employee First Name.\n";
cin >> firstName;
cout << "Please enter the new employee Last Name.\n";
cin >> lastName;
cout << "Please enter the new employee's ID.\n";
cin >> employeeID;
cout << "Please enter the new employee Phone Number.\n";
cin >> phoneNumber;
employee[10].first_name = firstName;
employee[10].last_name = lastName;
employee[10].employee_id = employeeID;
employee[10].phone_number = phoneNumber;
for (int i = 0; i < size; i++) {
cout << employee[i].first_name << "\t\t\t" << employee[i].last_name << "\t\t" << employee[i].employee_id << "\t\t" << employee[i].phone_number << "\n ";
cout << endl;
}
return employee;
}
First of all, your naming could be better. Like employeeList instead employee to specify its a list/array of employee, also addEmployee instead of getAddEmployee.
Second, instead of pasting whole code, it's better to paste the relevant block of code based on your question to make it clearer.
The solution is, your array is basically already on global scope, you don't need to pass it. Can just directly modify the array.
struct Data {
string first_name;
string last_name;
int employee_id;
string phone_number;
};
void addEmployee();
const int SIZE = 15;
Data employeeList[SIZE];
int current = 0;
int main(){
Data emp1 = {"John", "Doe", 100, "12345"};
employeeList[0] = emp1;
current++;
addEmployee();
for(int i=0; i<current; i++){
Data emp = employeeList[i];
cout<<i+1<<" "<<emp.first_name<<" "<<emp.phone_number<<endl;
}
}
void addEmployee(){
Data emp2 = {"Sam", "Smith", 200, "67890"};
employeeList[current] = emp2;
current++;
}
Can try it here: https://onlinegdb.com/drhzEOpis
In the code I shared below, I want to output vector data type in the AddStoreCustomer() section. This is how the code works. But there is a bug in the code. If I enter a single word in the customer variable, the code works fine. But when I enter two words in this variable with a space between them,the code doesn't work.
#include <iostream>
#include <vector>
using namespace std;
class Store {
int StoreID;
string StoreName;
string StoreCity;
string StoreTown;
string StoreTel;
vector <string> StoreCustomer;
public:
Store(){}
Store(int sid, string sname, string scity, string stown, string stel, string scustomer) {
setStoreID(sid);
setStoreName(sname);
setStoreCity(scity);
setStoreTown(stown);
setStoreTel(stel);
setStoreCustomer(scustomer);
}
void setStoreID(int sid) {
StoreID = sid;
}
void setStoreName(string sname) {
StoreName = sname;
}
void setStoreCity(string scity) {
StoreCity = scity;
}
void setStoreTown(string stown) {
StoreTown = stown;
}
void setStoreTel(string stel) {
StoreTel = stel;
}
void setStoreCustomer(string scustomer) {
StoreCustomer.push_back(scustomer);
}
int getStoreID() {
return StoreID;
}
string getStoreName() {
return StoreName;
}
string getStoreCity() {
return StoreCity;
}
string getStoreTown() {
return StoreTown;
}
string getStoreTel() {
return StoreTel;
}
vector <string> getStoreCustomer() {
return StoreCustomer;
}
~Store(){}
};
Store s2[50];
void AddStore() {
int id, menu;
string name, city, town, tel;
for (int i = 0; i < 1; i++) {
cout << "Lutfen Magaza ID Numarasini Girin: ";
cin >> id;
s2[i].setStoreID(id);
cout << "Lutfen Magaza Adini Girin: ";
cin >> name;
s2[i].setStoreName(name);
cout << "Lutfen Magazanin Bulundugu Ili Girin: ";
cin >> city;
s2[i].setStoreCity(city);
cout << "Lutfen Magazanin Bulundugu Ilceyi Girin: ";
cin >> town;
s2[i].setStoreTown(town);
cout << "Lutfen Magazanin Telefon Numarasini Girin: ";
cin >> tel;
s2[i].setStoreTel(tel);
cout << "Magaza Eklendi" << endl;
cout << "\n\n";
}
cout << "Menuye Donmek icin 0 " << endl;
cin >> menu;
if (menu == 0) {
StoreMenu();
}
else {
cout << "Tanımlanamayan Giris!!!" << endl;
//Menu();
}
}
int Search2(const int& y) {
for (int j = 0; j < 100; j++) {
if (s2[j].getStoreID() == y)
return j;
}
return -1;
}
void AddStoreCustomer() {
int id, found, menu;
string customer;
cout << "Lutfen Musteri Eklemek Istediginiz Magazanin ID Numarasini Girin:";
cin >> id;
found = Search2(id);
if (found == -1)
{
cout << "Magaza Bulunamadi" << endl;
}
else {
cout << "Magaza Bulundu.\n" << "Lutfen Magaza Veri Tabanina Eklemek Istediginiz Musterinin Bilgilerini Girin: ";
cin >> customer;
s2[found].setStoreCustomer(customer);
cout << "Girilen Musteri Bilgisi Secilen Magazaya Eklendi";
cout << "Magaza ID: " << s2[found].getStoreID() << "\n Magaza Adi: " << s2[found].getStoreName() << "\n Magazanin Bulundugu Il: " << s2[found].getStoreCity() << "\n Magazanin Bulundugu Ilce:" << s2[found].getStoreTown() << "\n Magaza Iletisim Numarasi: " << s2[found].getStoreTel() << endl;
cout << "Musteriler: " << endl;
for (int i = 0; i < s2[found].getStoreCustomer().size(); i++)
{
cout << "\t\t" << s2[found].getStoreCustomer()[i] << endl;
}
}
cout << "Tekrar Giris Yapmak icin 1 Menuye Donmek icin 0 " << endl;
cin >> menu;
if (menu == 0) {
StoreMenu();
}
else if (menu == 1) {
AddStoreCustomer();
}
This happens because you are using cin>> to read input, which reads until the first whitespace symbol. If you want to read a whole line, consider using std::getline() instead:
getline(cin, customer);
#include<iostream>
using namespace std;
int main()
{
int age;
char name;
cout<<"Enter age and name: ";
cin >> age >> name;
cout <<endl <<"your age: "<< age << endl << "name is: "<< name;
return 0;
}
What a run looks like:
Use a string instead of a char. A character only gets the first letter of the input.
The code should look like this.
#include<iostream>
using namespace std;
int main() {
int age = 0;
string name = "";
cout<<"Enter your age and name: ";
cin >> age >> name;
cout << endl;
cout << "Your age is " << age << endl;
cout << "Your name is " << name << endl;
return 0;
}
If you are required to use a character, you can try using a vector.
#include <iostream>
#include <vector>
using namespace std;
vector<char> _myStr;
void DisplayList () {
cout << "Your name is: ";
for (int i = 0; i < _myStr.size(); i++) {
cout << _myStr[i];
}
cout << endl;
}
void ConvertToVector (string theStr) {
for (int i = 0; i < theStr.length(); i++) {
_myStr.push_back(theStr[i]);
}
}
int main () {
int age = 0;
string name = "";
cout << "Enter your age and name: ";
cin >> age >> name;
cout << endl;
ConvertToVector (name);
cout << "Your age is: " << age;
DisplayList ();
return 0;
}
Use string instead of char...
#include<iostream>
#include <string>
using namespace std;
int main()
{
int age;
string name;
cout<<"Enter age and name: ";
cin >> age >> name;
cout <<endl <<"your age: "<< age << endl << "name is: "<< name;
return 0;
}
I am working on a project and I'm a beginner. The project involves a person, adult, kid and bogie class. In bogie class I have initialsed pointer of type person named adult as adult = new Adult [adultcount], where adultcount is the number of adults user wants to add.
When I add only one adult in input, it works fine, it takes the input and assigns it in while assigning values in for loop.
But when I add more than one, it stops working and says exception throw at line Adults[i].setdata().
#include<iostream>
#include<string>
using namespace std;
class Person {
public:
string Name;
int Age;
string Gender;
public:
Person()
{
Name = '\0';
Age = 0;
Gender = '\0';
}
Person(string Name, int Age, string Gender)
{
this->Name = Name;
this->Age = Age;
this->Gender = Gender;
}
virtual void setdata()
{
string name, gender;
int age;
cin.ignore();
cout << " enter Name :";
getline(cin, name, '\n');
this->Name = name;
cout << endl;
cout << " Enter gender ";
getline(cin, gender, '\n');
this->Gender = gender;
cout << endl;
cout << " Enter age ";
cin >> age;
Age = age;
cout << endl;
}
virtual void printinfo()
{
cout << " name " <<Name;
cout << " Gender " << Gender;
cout << " age : " << Age;
}
};
class Adult :public Person {
public:
string Occupation;
string Qualification;
string NIC;
Adult():Person()
{
Occupation = '\0';
Qualification = '\0';
NIC = '\0';
}
Adult(string Occupation, string Qualification, string NIC, string Name, int Age, string Gender) : Person(Name, Age, Gender)
{
this->Occupation = Occupation;
this->NIC = NIC;
this->Qualification = Qualification;
}
void setdata()
{
Person::setdata();
string occupation, qualification/*, name, gender,*/ ,cnic;
/* int age;*/
cin.ignore();
/* cout << " enter Name :" ;
getline(cin, name, '\n');
this->Name = name;
cout << endl;*/
cout << "enter occupation ";
getline(cin, occupation, '\n');
this->Occupation = occupation;
cout << endl;
/*cout << " Enter gender ";
getline(cin, gender, '\n');
this->Gender = gender;
cout << endl;*/
cout << " enter qualification ";
getline(cin, qualification, '\n');
this->Qualification = qualification;
cout << endl;
cout << " Enter cnic ";
getline(cin, cnic, '\n');
this->NIC = cnic;
cout << endl;
/* cout << " Enter age ";
cin >> age;
this->Age = age;
cout << endl;*/
}
void printinfo()
{
Person::printinfo();
/*cout << " name "<<Name << endl;*/
cout << " occupation " << Occupation << endl;
/*cout << " Gender " << Gender << endl;*/
cout << " Qualifcation " << Qualification << endl;
/*cout << " Age " << Age << endl;
cout << " Gender " << Gender << endl;*/
}
};
class kid :public Person {
public:
string B_form_number;
kid() : Person()
{
B_form_number = '\0';
}
kid(string B_form_number, string Name, int Age, string Gender) :Person(Name, Age, Gender)
{
this->B_form_number = B_form_number;
}
void setdata()
{
Person::setdata();
string bform;
cout << " Enter B Form number ";
/* getline(cin, bform, '\n')*/;
cin >> bform;
this->B_form_number = bform;
cout << endl;
}
void setbform()
{
string bform;
cout << " Enter B Form number ";
getline(cin, bform, '\n');
this->B_form_number = bform;
cout << endl;
}
void printinfo()
{
Person::printinfo();
cout << " b form number " << B_form_number;
}
};
class Bogie /*:public kid*/ {
int Bogie_ID;
Bogie* next;
Person* Adults;
Person* kids;
string familyName;
int adultcount;
int kidcount;
public:
Bogie(int id)
{
Bogie_ID = id;
next = nullptr;
Adults = nullptr;
kids = nullptr;
familyName = '\0';
adultcount = 0;
kidcount = 0;
}
void AddPassengers() // should add adults and kids information etc
{
string familyName;
cout << "Enter family name " << endl;
cin.ignore();
getline(cin, familyName, '\n');
this->familyName = familyName;
bool condition = false;
bool condition2 = false;
while (condition == false) // runs until valid input for adults
{
cout << " How many adults in the family " << endl;
cin >> adultcount;
if (adultcount >= 1 && adultcount <= 4)
{
condition = true;
}
else
{
cout << " Invalid input " << endl;
cout << " We have seats for 4 adults " << endl;
condition = false;
}
}
while (condition2 == false) //runs until valid input for kids
{
cout << " How many kids in the family " << endl;
cin >> kidcount;
if (kidcount >= 1 && kidcount <= 6)
{
condition2 = true;
}
else
{
cout << " Invalid input " << endl;
cout << " We have seats for 6 kids " << endl;
condition2 = false;
}
}
this->Adults = new Adult[adultcount];
for (int i = 0; i < adultcount; i++)
{
Adults[i].setdata();
}
}
}
};
int main()
{
Bogie a(1);
a.AddPassengers();
a.Print();
}
I believe you need to change Adults from Person * to Adult *.
When the program tries to access Adults[1] at
for (int i = 0; i < adultcount; i++)
{
Adults[i].setdata();
}
It jumps ahead sizeof(Person) in the array, while the objects in the array are sizeof(Adult), which leads to the exception you're seeing.
so I found the answer the appropriate method to to it was declaring pointers named adult and kid in the members as
Person ** Adults;
Person **kids
and then
adults = new Person * [adultcount];
for (int i = 0; i < adultcount; i++)
{
adults[i] = new Adult;
adults[i]->setdata();
}
I am very new to programming and I was trying to create a phone book application involve arrays. I want to essentially take a large number of contact's info and have the person be able to search for them.
Every time I try to compile the code, it works, and then when I press 1 to enter a contact and I enter the first name, I get this "Unhandled exception at 0x000f2ceb in assignment7.23.exe: 0xC0000005: Access violation reading location 0x99d0627c."
I'm not sure what this means or what is wrong with my code.
Thank you in advance.
#include <iostream>
#include <string>
using namespace std;
class AddressBook {
public:
string myContactsFirstName[100];
string myContactsLastName[100];
string myContactsEmailAddress[100];
string myContactsPhone[100];
int index;
AddressBook() {
int index = 0;
for (int i = 0; i < 100; i++) {
myContactsFirstName[i] = "";
myContactsLastName[i] = "";
myContactsEmailAddress[i] = "";
myContactsPhone[i] = "";
}
}
void addContact() {
cout << "Enter the first name of the contact: " << endl;
string firstname;
cin >> firstname;
myContactsFirstName[index] = firstname;
cout << "Last Name:" << endl;
string lastname;
cin >> lastname;
myContactsLastName[index] = lastname;
cout << "Phone Number: " << endl;
string phone;
cin >> phone;
myContactsPhone[index] = phone;
cout << "Email Address: " << endl;
string address;
cin >> address;
myContactsEmailAddress[index] = address;
system("pause");
index++;
}
void deleteLastContact(){
myContactsFirstName[index] = "";
myContactsLastName[index] = "";
myContactsPhone[index] = "";
myContactsEmailAddress[index] = "";
index--;
cout << "Contact deleted." << endl;
}
};
int main() {
AddressBook myPeople;
string target;
while(1){
cout << "Enter 1 to add a contact." << endl;
cout << "Enter 2 to search contacts." << endl;
cout << "Enter 3 to delete a contact." << endl;
cout << "Enter anything else to leave the program" << endl;
int choice;
cin >> choice;
switch (choice) {
case 1: myPeople.addContact();
break;
case 2: {
cout << "Enter the info to search for your contact:" << endl;
cin >> target;
for (int i = 0; i < myPeople.index; i++) {
if (myPeople.myContactsFirstName[i].compare(target) == 0 )
cout << "We have a match" << endl;
}
break;
}
case 3: {
myPeople.deleteLastContact();
break;
}
default: exit(0);
}
}
system("pause");
return 0;
}
Index is uninitialized:
AddressBook() {
int index = 0; //created a new index variable, fix this by deleting "int"
^^^
for (int i = 0; i < 100; i++) {
myContactsFirstName[i] = "";
myContactsLastName[i] = "";
myContactsEmailAddress[i] = "";
myContactsPhone[i] = "";
}
}