I have created a class called User:
has 4 private variables
a get_input() and print_output() function
a main function where I am accepting user input, where I have to initialize a new set of variables to pass the user input to the get_input() function
My question is: Do I have to define a new set of variables? Or is there any way to name, DOB, etc. directly to the get_input() function?
Here's my code:
#include <iostream>
#include <vector>
#include <string>
class User
{
private:
std::string name;
std::string DOB;
std::string telephone_no;
std::string add;
public:
int main();
User()
{
name = "";
DOB = "";
telephone_no = "";
add = "";
}
void get_input(std::string &name , std::string &DOB , std::string &telephone_no , std::string &add)
{
this->name = name;
this->DOB = DOB;
this->telephone_no;
this->add = add;
}
void print_output()
{
std::cout << name;
std::cout << DOB;
std::cout << telephone_no;
std::cout << add;
}
};
int main()
{
std::string name;
std::string DOB;
std::string telephone_no;
std::string add;
std::vector<std::string> ;
User obj ;
std::cout << "Enter the name of the user : ";
std::cin >> name;
std::cout << "Enter the date of birth of the user : ";
std::cin >> DOB;
std::cout << "Enter the telephone number of the user : ";
std::cin >> telephone_no;
std::cout << "Enter the address of the user : ";
std::cin >> add;
obj.get_input(name , DOB , telephone_no , add);
obj.print_output();
}
Followed the advice of Sam Varshachik
and changed my program accordingly:
You should input the variables first, then pass them to the class's constructor, when creating an instance of the class, which will use them to construct its private members
#include <iostream>
#include <vector>
#include <string>
class User
{
private :
std::string name;
std::string DOB;
std::string telephone_no;
std::string add;
public :
User(std::string &name , std::string &DOB , std::string &telephone_no , std::string &add)
{
this->name = name;
this->DOB = DOB;
this->telephone_no;
this->add = add;
}
void print_output()
{
std::cout << name;
std::cout << DOB;
std::cout << telephone_no;
std::cout << add;
}
};
int main()
{
//initializing local variables
std::string name;
std::string DOB;
std::string telephone_no;
std::string add;
std::vector<std::string> v;
//prompting the user to get essential details
std::cout << "Enter the name of the user : ";
std::cin >> name;
std::cout << "Enter the date of birth of the user : ";
std::cin >> DOB;
std::cout << "Enter the telephone number of the user : ";
std::cin >> telephone_no;
std::cout << "Enter the address of the user : ";
std::cin >> add;
//passing the entered_input into the object variables
User obj(name , DOB , telephone_no , add);
obj.print_output();
}
Related
I'm trying to practice with the usage of the new operator to create objects. I'm having some trouble with adjusting my code to manage the new pointers to the objects that I created.
Here's my code:
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <vector>
using namespace std;
struct StudentRecord {
public:
StudentRecord(
string id,
string firstName,
string lastName,
int age,
string phoneNumber,
double gpa
) {
Id = id;
FirstName = firstName;
LastName = lastName;
PhoneNumber = phoneNumber;
Age = age;
Gpa = gpa;
}
void display() {
cout << " Student ID: " << Id << endl;
cout << " First Name: " << FirstName << endl;
cout << " Last Name: " << LastName << endl;
cout << " Phone Number: " << PhoneNumber << endl;
cout << " Age: " << Age << endl;
cout << " GPA: " << Gpa << endl;
cout << endl;
}
string Id;
string FirstName;
string LastName;
string PhoneNumber;
int Age;
double Gpa;
};
void displayStudents(vector<StudentRecord>& students) {
for (auto student : students) {
student.display();
}
}
int main()
{
ifstream inputFile;
inputFile.open("TestFile.csv");
string line = "";
vector<StudentRecord> students;
while (getline(inputFile, line)) {
stringstream inputString(line);
//StudentId, Last Name, FirstName, Age, Phone Number, GPA
string studentId;
string lastName;
string firstName;
int age;
string phone;
double gpa;
string tempString;
getline(inputString, studentId, ',');
getline(inputString, lastName, ',');
getline(inputString, firstName, ',');
getline(inputString, tempString, ',');
age = atoi(tempString.c_str());
getline(inputString, phone, ',');
getline(inputString, tempString);
gpa = atof(tempString.c_str());
students.push_back(new StudentRecord(studentId, lastName,firstName, age, phone, gpa));
line = "";
}
displayStudents(students);
}
Specifically there's an issue here:
students.push_back(new StudentRecord(studentId, lastName,firstName, age, phone, gpa));
I know that I need to adjust the displayStudents function to take in a vector of pointers to the object, but I'm not sure how to do this.
students is of type vector<StudentRecord>, therefore, you don't need to call new.
If you wanted to practice new, suggest changing it to vector<StudentRecord*>. Note that it's recommended to use a managed pointer type (e.g. unique_ptr, smart_ptr) instead of 'naked' pointers.
If you'd simply like to make the code work, use:
students.emplace_back(studentId, lastName,firstName, age, phone, gpa));
In either case, you might consider std::move() on locally-generated strings that you only use here, i.e., std::move(studentId), std::move(lastName), ... in the arguments of emplace_back() or push_back().
I wanna ask you quick question. How can get the name, surname, id and age as an input? These are must be taken as input and variables must be private. How should I code about it?
#include <iostream>
using namespace std;
class Employee{
private:
string Name;
string Surname;
int IdNumber;
int age;
public:
Employee(string isim,string soyisim,int idnumarasi,int yas){
Name = isim;
Surname = soyisim;
IdNumber = idnumarasi;
age = yas;
}
void printEmployee(){
cout << Name << endl;
cout << Surname << endl;
cout << IdNumber <<endl;
cout << age << endl;
}
};
int main() {
Employee employee("John","Lares",12,25);
employee.printEmployee();
return 0;
}
Edited version. I used getline but still cant reach the private variables. How can reach the private variables. Is the only way getter setter functions?
#include <iostream>
using namespace std;
class Employee{
private:
string Name;
string Surname;
int IdNumber;
int age;
public:
Employee(){
Name = isim;
Surname = soyisim;
IdNumber = idnumarasi;
age = yas;
}
void printEmployee(){
cout << Name << endl;
cout << Surname << endl;
cout << IdNumber <<endl;
cout << age << endl;
}
};
int main() {
Employee employee();
getline(cin,employee.Name);
getline(cin,employee.Surname);
getline(cin,employee.IdNumber);
getline(cin,employee.age);
employee.printEmployee();
return 0;
}
One simple way is to use the constructor you have defined
int main()
{
string name, surname;
int id, age;
cin >> name >> surname >> id >> age; // read user input
Employee someone(name, surname, id, age); // create employee from user input
...
}
Using a constructor is the normal way to give class member variables their initial values.
Another more complicated way is to overload operator>>
I have a class:
class Account {
private:
string name;
unsigned int age;
string username;
string password;
};
In my main program I need to make a bool usernameExsist(Account* userAccount, Account* acountList[], int numberOfElements) function that returns true if the name is found. But I have problems with the arrays and the implementation.I entered some information in the class: Account first=Account("Max", 18,"maxx34","12345adc");Can someone help me with the implementation?! Thanks.
You can use class vector which relieve you from the burden of arrays and size...
Here is an example that you could modify to meet your needs:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class Account {
public:
Account(string, unsigned int, string, string);
//private: // in your example un-comment private and provide public getters instead.
string name;
unsigned int age;
string username;
string password;
};
Account::Account(string Name, unsigned int Age, string UserName, string Password) :
name(Name), age(Age), username(UserName), password(Password){
}
bool usernameExsist(string, vector<Account>);
int main(){
std::vector< Account > vec;
string name;
unsigned int age;
string username;
string password;
while(1){
cout << "name: ";
getline(cin, name);
cin.ignore();
cout << "Age: ";
cin >> age;
if(!age || age < 0)
break;
cin.ignore();
cout << endl;
cout << "username: ";
getline(cin, username);
cin.ignore();
cout << endl;
cout << "password: ";
getline(cin, password);
cout << endl;
cin.ignore();
Account a(name, age, username, password);
vec.push_back(a);
}
cout << usernameExsist("Max", vec) << endl;
cout << endl;
return 0;
}
bool usernameExsist(string name, vector<Account> vec){
const int size = vec.size();
for(int i(0); i != size; ++i)
if(name == vec[i].name){
cout << "Found at: " << i << endl;
return true;
}
return false;
}
Throwing this out there first I'm a still learning how to program in school. I'm having an issue reading in to a dynamically created array with a pointer to one of my classes. The function readClassArray() isn't getting the variable back from student.getCreditNumber. The program complies fine in Visual Studio but when I get the the readClassArray it just skips over the function because s.getCreditNumber returns 0.
#ifndef STUDENT_H
#define STUDENT_H
#include <iostream>
using namespace std;
class Courses{
private:
int courseNumber;
double hours;
string courseName;
char grade;
public:
void setCourseNumber(int n){courseNumber = n; }
void setCreditHours(double c) { hours = c; }
void setCourseName(string n) { courseName = n; }
void setGrade(char g) { grade = g; }
int getCourseNumber() { return courseNumber; }
double getCreditHours() { return hours; }
string getCourseName() { return courseName; }
char getGrade() { return grade; }
};
class Student : public Courses{
private:
string firstName;
string lastName;
string studentNumber;
int creditNumber;
double gpa;
public:
Courses * courses;
Student() {
firstName = " ";
lastName = " ";
studentNumber = " ";
creditNumber = 0;
gpa = 0.0;
courses = NULL;
}
~Student() {
delete[] courses;
};
void setFirstName(string n) { firstName = n; }
void setLastName(string l) { lastName = l; }
void setStudentNumber(string a) { studentNumber = a; }
void setCreditNumber(int num) { creditNumber = num; }
string getFirstName() { return firstName; }
string getLastName() { return lastName; }
string getStudentNumber() { return studentNumber; }
int getCreditNumber() { return creditNumber; }
};
#endif
Student.cpp
#include "Student.h"
#include <iostream>
#include <string>
using namespace std;
void readStudent();
void readCourseArray();
void computeGPA();
void printSummary();
void readStudent() {
Student a;
string number;
string firstName;
string lastName;
int courses;
cout << "Enter student number: ";
cin >> number;
a.setStudentNumber(number);
cout << "Enter student first name: ";
cin >> firstName;
a.setFirstName(firstName);
cout << "Enter student last name: ";
cin >> lastName;
a.setLastName(lastName);
cout << "Enter student number of courses: ";
cin >> courses;
a.setCreditNumber(courses);
cout << "\n"; }
void readCourseArray(){
Student s;
s.courses = new Courses[s.getCreditNumber()];
int num;
double cHours;
string cName;
char grade;
cout << "test" << endl;
for (int i = 0; i < s.getCreditNumber(); i++){
cout << "Enter class " << i + 1 << " number: ";
cin >> num;
s.courses[i].setCourseNumber(num);
cout << "Enter class " << i + 1 << " name: ";
cin >> cName;
s.courses[i].setCourseName(cName);
cout << "Enter class " << i + 1 << " hours: ";
cin >> cHours;
s.courses[i].setCreditHours(cHours);
cout << "Enter class " << i + 1 << " grade: ";
cin >> grade;
s.courses[i].setGrade(grade);
cout << "\n";
}
}
At the start of readCourseArray you've created s. When that happens the value of the creditNumber member is 0 as set by the default constructor. You need to do something to set it to a non-zero value. If you're expecting the value set in readStudent to carry over you need to plumb the two functions together. Either pass in a Student object as a reference to each function, or have readStudent return a Student object and pass that to readCourseArray.
Everything in my coding works except the get and set name functions. When I call getName, it prints blank. I've tried a few different solutions, but the only thing that has worked is actually saving the fullName string inside of main, and calling it from there. It's almost as if it's not letting me call the variables because they are private.
Here is my .cpp file.
#ifndef STUDENT_H
#define STUDENT_H
#include <iostream>
#include <string>
#include "Student.h"
using namespace std;
int main()
{
//for student name
string firstName;
string lastName;
string fullName;
//student name
cout << "Please enter your students first name" << endl;
cin >> firstName;
cout << "firstName = " << firstName << endl;
cout << "Please enter your students last name" << endl;
cin >> lastName;
cout << "lastName = " << lastName << endl;
aStudent.setName(firstName, lastName);
fullName = aStudent.getName();
cout << "Your students name is : ";
cout << fullName << endl;
}
#endif
Here are my functions, and class, .h file.
#include <iostream>
#include <string>
#include <conio.h>
using namespace std;
class Student
{
private:
string fName;
string lName;
public:
string getName();
void setName(string firstName, string lastName);
};
string Student::getName()
{
return fName + " " + lName;
}
void Student::setName(std::string firstName, std::string lastName)
{
firstName = fName;
lastName = lName;
}
void Student::setName(std::string firstName, std::string lastName)
{
firstName = fName;
lastName = lName;
}
Surely you see the problem there. Hint, assignment copies the thing on the right to the thing on the left.
void Student::setName(std::string firstName, std::string lastName)
{
firstName = fName; // you're assigning the local firstName to your class instance's
lastName = lName; // variable; reverse this and try again
}
// ...
void Student::setName(std::string firstName, std::string lastName)
{
fName = firstName;
lName = lastName;
}