My string isn't copying from private variables - c++

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;
}

Related

Vectors of Pointers passed into different functions

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().

How to accept user input in a class when using private variables?

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();
}

C++ Class getting input

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>>

How to get my CSV File reader to read different types in C++?

For my project, my program has to read a file that looks like this: "Mary", "000111222", "Junior", 12, 4.0
In my main code it can read it, but only as strings only. I want it to read it as string,string, string, float, float. The getLine() method only works with strings. I tried other ways but it did not work. Any suggestions? The fields I want to be a float is gpa and credit. Any advice is appreciated! Thank you!
#include <iostream>
#include <string>
#include <iterator>
#include <iomanip>
#include <fstream>
#include <vector>
include <sstream>
#include <algorithm>
using namespace std;
class Student {
//declare local variables
protected:
string name; //people with names longer than 21 characters will just have
to make do
string ssn; // Social Secturity Number.
string gpa; //Most up to date gpa for the student
string credits; //Number of student's credit hours
//build public methods
public:
//Default Constructor
Student() {}
//Student constructor. Besides the character arrays, everything else is
passed by reference.
Student(const string n, const string s, string sGPA, string sCredits) {
name = n;
ssn = s;
gpa = sGPA;
credits = sCredits;
}
string getName() {
return name;
}
string getSSN() {
return ssn;
}
string getGPA() {
return gpa;
}
string getCredit() {
return credits;
}
//a function that is expected to be implemented and overridden by subclasses
virtual void print() const {
cout << '\n' << endl;
cout << "Student's name: " << name << endl;
cout << "Student SSN: " << ssn << endl;
cout << "Student's current GPA: " << gpa << endl;
cout << "Student's credit hours: " << credits << endl;
}
// a pure virtual function for implementation later. Makes whole class
Abstract
virtual float tuition() const = 0;
};
class Undergrad : public Student {
//declare local variables
protected:
float undergrad_rate = 380.0;
string year;
//build public methods
public:
//Default Constructor
Undergrad() {}
//Undergrad Constructor
Undergrad(const string n, const string s, string uGPA, string uCredits,
string y) :
Student(n, s, uGPA, uCredits), year(y) {}
//Display the contents of undergrad
void print() const {
Student::print();
cout << "Undergrad Rate: " << undergrad_rate << endl;
cout << "Year: " << year << endl;
}
//Display undergrad's current year
string get_year() {
return year;
}
//Display the undergrad's current rate
float get_rate() {
return undergrad_rate;
}
//Set a undergrad's current year
void set_year(string y) {
year = y;
}
//Display the cost for an undergrad to attend university
float tuition() const {
return 1000000;
}
};
int main() {
ifstream ip("data.txt");
if (!ip.is_open()) std::cout << "ERROR: File not found" << '/n';
string name;
string ssn;
string year;
string credit;
string gpa;
vector<Undergrad> file;
//Undergrad g(name, ssn, year, credit, gpa);
while (ip.good()) {
getline(ip, name, ',');
getline(ip, ssn, ',');
getline(ip, gpa, ',');
getline(ip, credit, ',');
getline(ip, year, '\n');
// float number = stoi(gpa);
//float number1 = stoi(credit);
Undergrad g(name, ssn, year, credit, gpa);
file.push_back(g);
}
ip.close();
Undergrad g = file.back();
file.pop_back();
file.insert(file.begin(),g);
for (int i = 0; i < file.size(); i++) {
cout << "Name: " << file[i].getName() << endl;
cout << "SSN: " << file[i].getSSN() << endl;
cout << "Year: " << file[i].get_year() << endl;
cout << "Credit: " << file[i].getCredit() << endl;
cout << "GPA " << file[i].getGPA() << endl;
cout << " " << endl;
}
system("pause");
return 0;
}
You can cast the string to a float using atof. See reference here. Be sure to include <cstdlib>. Your constructor would look like:
Student(const string n, const string s, string sGPA, string sCredits) {
name = n;
ssn = s;
gpa = (float)atof(sGPA.c_str());
credits = (float)atof(sCredits.c_str());
}

How to determine if name and lname is not in file

The program, is basically sussposed to iterate a file containing the elements
Harry Keeling (202)806-4830
Frank James (301)123-3459
Arthur Paul (202)865-9090
Todd Shurn (410)560-8909
Richard Okpala 202 388 410
what my current program is outputting the phonenumber if firstname and lastname is present in file but if its nothow do i output phone number isnt here my current code.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void lookup_name(ifstream&, string&, string&, string&); // prototype
int main()
{
ifstream myfile;
string name, lastname, phonenumber;
char choice;
do
{
myfile.open("infile.txt");
cout << "What is the First name? " << endl;
cin >> name;
cout << "what is your last name?" << endl;
cin >> lastname;
lookup_name(myfile, name, lastname, phonenumber);
cout << "Do you want to lookup another name<Y/N" << endl;
cin >> choice;
} while (choice == 'Y');
return 0;
}
void lookup_name(ifstream& myfile, string& name, string& lastname, string& phonenumber)
{
string name1, name2, fullname, secondname, dummy;
for (int i = 0; i < 5; i++) {
myfile >> name1 >> name2;
fullname = name1 + name2;
secondname = name + lastname;
if (fullname == secondname) {
myfile >> phonenumber;
cout << phonenumber << endl;
myfile.close();
break;
}
else if (fullname != secondname) {
myfile >> dummy;
phonenumber = dummy;
}
Just return whether you found it or not from your lookup function
int lookup_name(ifstream& myfile, string& name, string& lastname, string& phonenumber)
{
string name1, name2, fullname, secondname, dummy;
for (int i = 0; i < 5; i++) {
myfile >> name1 >> name2;
fullname = name1 + name2;
secondname = name + lastname;
if (fullname == secondname) {
myfile >> phonenumber;
cout << phonenumber << endl;
myfile.close();
return 1;
}
else if (fullname != secondname) {
myfile >> dummy;
phonenumber = dummy;
}
}
return 0;
}
Then use the return value
if ( ! lookup_name(myfile, name, lastname, phonenumber) ) {
cout << "Nope, didn't find it!" << endl;
}