My output name is not being displayed in my program. I have been looking at the code and
I just can't find my error
input
name : John Dough
id : 123445
start date : 10312014
shift: 2
output
name : ^^^^^^ <<<< I am having problem my name not being displayed
id : 123445
start date : 10312014
shift : 2
code
//This program demostrates a class and a derived class with constructors.
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
class Employee
{
private:
char EmpName;
int EmpNum;
int HireDate;
public:
void setEmpName(char);
void setEmpNum(int);
void setHireDate(int);
char getEmpName() const;
int getEmpNum() const;
int getHireDate() const;
Employee();
};
void Employee::setEmpName(char x)
{
EmpName = x;
}
void Employee::setEmpNum(int y)
{
EmpNum = y;
}
void Employee::setHireDate(int z)
{
HireDate = z;
}
char Employee::getEmpName() const
{
return EmpName;
}
int Employee::getEmpNum() const
{
return EmpNum;
}
int Employee::getHireDate() const
{
return HireDate;
}
Employee::Employee()
{
cout << "I will ask you some questions about an employee.\n\n";
}
class ProductionWorker : public Employee
{
private:
int Shift;
double HourlyPayRate;
public:
void setShift(int);
void setHourlyPayRate(double);
int getShift() const;
double getHourlyPayRate() const;
ProductionWorker();
};
void ProductionWorker::setShift(int a)
{
Shift = a;
}
void ProductionWorker::setHourlyPayRate(double b)
{
HourlyPayRate = b;
}
int ProductionWorker::getShift() const
{
return Shift;
}
double ProductionWorker::getHourlyPayRate() const
{
return HourlyPayRate;
}
ProductionWorker::ProductionWorker()
{
cout << "After answering the questions,\n";
cout << "I will display the employee's information.\n\n\n";
}
int main()
{
ProductionWorker info;
char name[100];
int num;
int date;
int shift;
double rate;
cout << "What is the employee's name? ";
cin.getline(name, 100);
cout << "What is the employee's number? ";
cin >> num;
cout << "What is the employee's hire date?\n";
cout << "(Month, day, and year without any slashes,\n";
cout << "dashes, commas, or other punctuation.)\n";
cout << "For example, January 14, 1983 would look like 01141983. ";
cin >> date;
cout << "Does the employee work shift 1 or shift 2? ";
cin >> shift;
cout << "How much does the employee make per hour? ";
cin >> rate;
info.setEmpName(name[100]);
info.setEmpNum(num);
info.setHireDate(date);
info.setShift(shift);
info.setHourlyPayRate(rate);
cout << "\n\nHere is the employee's data:\n\n";
cout << "Employee's Name: " << info.getEmpName() << endl;
cout << "Employee's Number: " << info.getEmpNum() << endl;
cout << "Employee's Hire Date: " << info.getHireDate() << endl;
cout << "Employee's Shift: " << info.getShift() << endl;
cout << setprecision(2) << fixed;
cout << "Employee's Hourly Pay Rate: $" << info.getHourlyPayRate() << endl << endl;
return 0;
}
This is wrong: you're accessing an out-of-range character instead of passing the array to the function
char name[100];
//.. initialize name..
info.setEmpName(name[100]); // Accesses the 100th character (out-of-range [0-99])
void Employee::setEmpName(char x)
{
EmpName = x;
}
I would go for using std::string by changing EmpName (also wrong, it's not a single character) to a std::string
class Employee
{
private:
string EmpName;
int EmpNum;
int HireDate;
public:
void setEmpName(std::string& name);
void setEmpNum(int);
void setHireDate(int);
string getEmpName() const;
int getEmpNum() const;
int getHireDate() const;
Employee();
};
Also don't forget to change char name[100] to a std::string in the main function.
Live Example
You can of course accomplish this also with char arrays, in that case if you intend to use a fixed-size array you could either pass it by reference or just copy the content of a pointer to the array into a memory array for Employee.
There are multiple problems with your code.
First, the data type of Employee::EmpName should not be char. It should be a char array or even better would be a std::string.
Second the parameter of the setEmpName function should be either a const char* or a const std::string&.
Third, the name variable should perhaps be a std::string instead of a char array. Of course if you make that change the parameter of the setEmpName function should be const std::string&.
Fourth, when calling the setEmpName function you should just call it as follows: info.setEmpName(name).
Next, you should use std::getline(cin, name) instead of cin.getline(name, 100).
I'm first correcting your mistakes and then giving you a better alternative solution.
The member of your class and the setter function's parameter are only a single char. Change them to arrays:
char EmpName[100];
and
void setEmpName(char[]);
and in the implementation, you need to copy the content of the given array to your member:
void Employee::setEmpName(char[] x) {
memcpy(EmpName, x, 100);
}
However, this is the C way to do this.
The C++ way to do this is to use std::string. For this, change the types of the member, the parameters in the setter and in the getter as well as the type in main to std::string. To read a std::string, use the free-standing overload of getline which only takes the stream and the string (but no count):
getline(cin, name);
Related
#include <iostream>
using namespace std;
class CSE
{
private:
char Name;
double Roll;
public:
void getN(char N, double RN)
{
Name = N;
Roll = RN;
}
};
char EnterName()
{
cout << "Enter the name of the student" << ;
}
char EnterRN()
{
cout << "enter the rn" << ;
};
int main()
{
CSE nnn;
nnn.getN(N, RN);
cout << "enter the name" << nnn.EnterName << endl;
cout << "enter the roll" << nnn.EnterRN << endl;
return 0;
}
What should I correct here for the right implementation of my code? I just want to keep the names and roll number private and then public them afterwards. I also want to enter the name and roll number by the user and then display it.
You are defining (free) functions instead declaring and defining a method:
class CSE {
...
public:
char EnterRN();
};
char CSE::EnterRN() {
...
}
If you want to do it inline then the closing } of the class needs to be after those functions.
I am doing my first C++ program for my class. I am really new to this program so I have a lot to learn. In my program I am suppose to create a Student class with Undergrad/grad/gradassist derived classes. The name and SSN fields have to be in a char array (I know string makes more sense but the teacher demands a char array). The program mostly works fine except it does not print anything in my char arrays. Please help!
#include <iostream>;
using namespace std;
class Student {
protected:
char name[21];
char ssn[10];
float gpa;
int credits;
public:
Student::Student() {};
Student(const char n[], const char ss[], float& gp, int& cred) {
name[21] = n[21];
ssn[10] = ss[10];
gpa = gp;
credits = cred;
}
virtual void print() {
cout << "Name: " << name << endl;
cout << "SSN: " << ssn << endl;
cout << "GPA: " << gpa << endl;
cout << "Credits: " << credits << endl;
}
virtual float tuition() const = 0;
};
class undergrad : public Student {
protected:
float undergrad_rate;
char* year;
public:
undergrad::undergrad() {}
undergrad(float ugr, char* yr, const char n[], const char ss[], float&
gp, int& cred) :
Student(n, ss, gp, cred), undergrad_rate(ugr), year(yr){}
void set_year(char* yr) {
year = yr;
}
char* getYear() {
return year;
}
float getRate() {
return undergrad_rate;
}
void print() {
Student::print();
cout << "Undergrad rate: " << undergrad_rate << endl;
cout << "year: " << year << endl;
}
float tuition() {
//cout << "The tuition is $35000" << endl;
return 35000;
}
};
class grad : public Student {
protected:
float grad_rate;
char* thesis;
public:
};
int main(){
char* jr = "Junior";
char* sr1 = "Senior";
char* fr = "Freshman";
char* sr = "Sophmore";
undergrad g(380, jr, "M", "000111222", 4.0, 12);
g.print();
system("pause");
return 0;
}
The problem lies here, in the way you initialize the members name and ssn:
Student(const char n[], const char ss[], float& gp, int& cred) {
name[21] = n[21];
ssn[10] = ss[10];
There's more than one thing wrong here
name and ssn are char arrays of size 21 and size 10 respectively. This means that valid indices range from 0 to 20 and 0 to 9 respectively. So by accessing name[21] and ssn[10] you're accessing elements past the end of the allotted memory.
Even if the indices were valid, you would just be assigning a single character by doing it this way.
In order to initialize these member variables the way you're intending, do this:
Student(const char n[], const char ss[], float& gp, int& cred) {
strcpy_s(name, sizeof(name), n);
strcpy_s(ssn, sizeof(ssn), ss);
This will copy all the characters comprising the input strings into your member variables and you will get the desired output.
i am trying to input a string in my code in c++ and when i run i always get the following error: Exception thrown at 0x0F5023F5 (msvcp140d.dll) in assignment-1.exe: 0xC0000005: Access violation writing location 0x00229C20. i will post my code below if anyone could help me that would be great.Please note that i already know that its a problem with me trying to access the memory location on which you dont have access to, i just dont know how to fix it.
HEADER FILE:
#ifndef item_H
#define item_h
class item
{
private:
//attributes
int itemID;
char itemName[20];
float itemcost;
float itemprice;
//utility function
float calcPrice();
public:
//constructor
item(int = 000, char[] = "itemUnknown", float = 0,float = 0);
//destructor
~item();
//set functions
void setAll(int, char[], float, float);
void setID(int);
void setName(char[]);
void setCost(float);
//get function
int getID();
float getcost();
float getprice();
void getname();
//print function
void print();
};
#endif
CPP:
#include "Dariush.h"
#include <iostream>
#include <iomanip>
#include<string>
using namespace std;
//constructor will set attributes
item::item(int ID, char n[] , float c,float p)
{
setID(ID);
setName(n);
setCost(c);
setAll(ID, n, c, p);
}
//destructor will print destroing two objects
item::~item()
{
cout << "destroing two objects : " << " " << itemName << " "
<< " & " << itemName << endl;
}
//set functions :
void item::setID(int ID)
{
cout << "please enter the item's ID : " << endl;
cin >> ID;
}
void item::setName(char n[])
{
cout << "please enter the item's name" << endl;
cin.ignore();
cin.getline(n, 20);
}
void item::setCost(float c)
{
cout << "please enter the item's cost : " << endl;
cin >> c;
}
void item::setAll(int ID, char n[], float c, float p)
{
itemID = (ID > 0 && ID < 999) ? ID : 0;
strcpy_s(itemName, n);
itemcost = (c > 0) ? c : 0;
calcPrice();
}
//get functions :
int item::getID()
{
return itemID;
}
float item::getcost()
{
return itemcost;
}
float item::getprice()
{
return itemprice;
}
void item::getname()
{
cout << itemName << endl;
}
//print function :
void item::print()
{
cout << "ID : " << itemID << endl
<< "Name : " << itemName << endl
<< "cost : " << itemcost << endl
<< "price : " << itemprice << endl;
}
// utility function for price callculation :
float item::calcPrice()
{
if (itemcost < 1000)
{
itemprice = itemcost + (itemcost*0.1);
}
else
itemprice = itemcost + (itemcost*0.2);
return itemprice;
}
MAIN.CPP:
#include "Dariush.h"
#include <iostream>
#include<string>
using namespace std ;
void main()
{
item i1;
item i2;
i1.print();
i2.print();
}
thanks for the assistance.
Lets take a closer look at these three function declarations:
item(int = 000, char[] = "itemUnknown", float = 0,float = 0);
void setAll(int, char[], float, float);
void setName(char[]);
The thing here is that the character "array" arguments you declare are not really arrays at all. Instead they are pointers. When declaring arguments, e.g. char n[] is actually translated by the compiler as char *n.
The constructor declaration makes the pointer point to the constant string literal "". And the important thing about constant string literals is that they are indeed constant. Trying to modify a string literal leads to undefined behavior. And change this literal is what you are trying to do with the cin.getline(n, 20) call in the setName function. Not only that, but you are also telling the cin.getline function to read more than fits in the string literal.
The simple solution is to have setName read into the member variable itemName instead.
There are many problems with this code, but the one that is causing the access violation is:
void item::setName(char n[])
{
cout << "please enter the item's name" << endl;
cin.ignore();
cin.getline(n, 20); //here
}
You should use cin.getline(itemName, 20); instead.
Also, to prevent such error in the future, declare arguments as char const n[] instead of char n[] - good compiler should display a warning when you use string literals with non-const pointer as argument.
So, the problem is several errors at compile time.
ReadMovieData(string* title, string* director) cannot convert from movieInfo to string*
DisplayMovieData(string title, string director) cannot convert from movieInfo to string
No operator found which takes a right-hand operand of type 'movieInfo' (or there is no acceptable conversion.
The bottom error happens twice in DisplayMovieData() so I wrote it once for simplicity sake.
The ReadMovieData function should accept a structure pointer reference variable and the DisplayMovieData function should accept a MovieInfo structure variable.
The main function creates an array of 2 MovieInfo struct variables and the other functions should be called on an element of the array.
The code I have finished is below.
#include <stdafx.h>
#include <string>
#include <iomanip>
#include <iostream>
using namespace std;
//prototypes
int ReadMovieData(string* title, string* director);
int DisplayMovieData(string title, string director);
struct movieInfo {
string title, director;
};
int main(){
const int SIZE = 2;
movieInfo movieList[SIZE];
movieInfo movie;
//supposed to assign data to movieList[i] at some point
for (int i = 0; i < SIZE; i++){
ReadMovieData(movie, movie);
DisplayMovieData(movie, movie);
}
return 0;
}
int ReadMovieData(movieInfo &title, movieInfo &director){
movieInfo movie;
//get the movie name
cout << "What is the movie? ";
cin.ignore();
cin >> movie.title;
//get the movie director
cout << "What is the director of " << movie.title << "?";
cin.ignore();
cin >> movie.director;
return 0;
}
int DisplayMovieData(movieInfo title, movieInfo director){
cout << "The movie name is: " << title << endl;
cout << "The director of " << title << " is: " << director << endl;
return 0;
}
There are mismatches between your function prototypes and their definitions, as you can see comparing the parameter types in both.
Note that since you defined a structure for the movie info, you can directly pass it to the reading and displaying functions (instead of passing the single structure data member strings).
You may want to read the following compilable code:
#include <iostream>
#include <string>
using namespace std;
struct MovieInfo {
string title;
string director;
};
void ReadMovieData(MovieInfo& movie);
void DisplayMovieData(const MovieInfo& movie);
int main() {
const int SIZE = 2;
MovieInfo movieList[SIZE];
for (int i = 0; i < SIZE; i++) {
ReadMovieData(movieList[i]);
DisplayMovieData(movieList[i]);
}
}
// Since movie is an output parameter in this case, pass by non-const reference.
void ReadMovieData(MovieInfo& movie) {
//get the movie name
cout << "What is the movie? ";
cin >> movie.title;
//get the movie director
cout << "What is the director of " << movie.title << "?";
cin >> movie.director;
}
// Since movie is an input parameter in this case, pass by reference to const.
void DisplayMovieData(const MovieInfo& movie) {
cout << "The movie name is: " << movie.title << endl;
cout << "The director of " << movie.title
<< " is: " << movie.director << endl;
}
The errors are pretty explanatory and clear - your function takes string* but you're passing movieInfo - unrelated types can't just magicaly convert one to another.
What you probably want is pass the data members of movieInfo:
ReadMovieData(&movie.title, &movie.director);
It would be better if arguments were not pointers - use references instead. Where you won't be changing the arguments, the references should be to const type.
Even better, why not just pass moveInfo
ReadMovieData(movieInfo& movie);
and let the function deal with the internals of the class? This better encapsulates data and doesn't lead to spaghetti code quite so fast.
Also, the declarations and definitions need to match (otherwise you'd be overloading) - you're using pointers in some places and references/values in others.
Finally, here's how an overload of operator<< might look like:
std::ostream& operator<<(std::ostream& os, const movieInfo& m)
{
return os << "Title: " << m.title << ", Director: " << m.director;
}
Your class movieInfo does not have an overloaded << operator, which is necessary is you want to work with iostream, however, you can pass the strings contained in movieInfo:
int DisplayMovieData(string &title, string &director) { }
Call like:
DisplayMovieData(movie.title, movie.director);
You are declaring the function with this signature
int ReadMovieData(string* title, string* director);
but you're defining it using
int ReadMovieData(movieInfo &title, movieInfo &director) {
// ...
}
These don't match!
The code is totally invalid. I suppose the valid code should look the following way
#include <stdafx.h>
#include <string>
#include <iomanip>
#include <iostream>
using namespace std;
struct movieInfo
{
string title, director;
};
//prototypes
movieInfo ReadMovieData();
void DisplayMovieData( const movieInfo & );
int main()
{
const int SIZE = 2;
movieInfo movieList[SIZE];
//supposed to assign data to movieList[i] at some point
for ( int i = 0; i < SIZE; i++ )
{
movieList[i] = ReadMovieData();
DisplayMovieData( movieList[i] );
}
return 0;
}
movieInfo ReadMovieData()
{
movieInfo movie;
//get the movie name
cout << "What is the movie? ";
cin.ignore();
cin >> movie.title;
//get the movie director
cout << "What is the director of " << movie.title << "?";
cin.ignore();
cin >> movie.director;
return movie;
}
void DisplayMovieData( const movieInfo &movie )
{
cout << "The movie name is: " << movie.title << endl;
cout << "The director of " << movie.title << " is: " << movie.director << endl;
}
Ok so i'm fairly new to c++ and this is my first try using vectors. My goal is to store objects into a vector. I'm trying to follow this youtube tutorial:
http://www.youtube.com/watch?v=iPlW5tSUOUM
and i think mine is pretty much the same apart from his runs.
I just keep getting errors and it won't run. Any help would be appreciated :)
Maybe it's something small, but i've been checking for a while now and i can't see anything.
Errors:
1>c:\users\user\desktop\vector objects c++\testvectorobjects\testvectorobjects\main.cpp(61): error C3867: 'Employees::getSalary': function call missing argument list; use '&Employees::getSalary' to create a pointer to member
1>c:\users\user\desktop\vector objects c++\testvectorobjects\testvectorobjects\main.cpp(61): error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'overloaded-function' (or there is no acceptable conversion)
1>c:\program files (x86)\microsoft visual studio 11.0\vc\include\ostream(695): could be 'std::basic_ostream<_Elem,_Traits> &std::operator <<>(std::basic_ostream<_Elem,_Traits> &,const char *)'
I have 3 files: main.cpp, Employee.h, Employees.cpp
//main.cpp
#include <iostream>
#include <string>
#include <vector>
#include "Employee.h"
void fillVector(vector<Employees>&);
//fill vector - fills in Employee Info
//vector<Employees>& - Employees at the station
void printVector(const vector<Employees>&);
//print vector - prints the employee info
//const vector<Employees>& - employees at the station
using namespace std;
vector<Employees> Staff;
int main(){
fillVector(Staff);
printVector(Staff);
}
//filling the employee vector
void fillVector(vector<Employees> & newStaff){
int id;
double salary;
string name;
cout << "Number of Employees" << endl;
int amountEmployees;
cin >> amountEmployees;
for (int i = 0; i < amountEmployees; i++) {
cout << "Enter Employee Id: ";
cin >> id;
cout << "Enter Employee Salary: ";
cin >> salary;
cout << "Enter Employee Name: ";
cin >> name;
Employees newEmployees(id, salary, name);
newStaff.push_back(newEmployees);
cout << endl;
}
cout << endl;
}
//printing the employee vector
void printVector(const vector<Employees>& newStaff){
unsigned int size = newStaff.size();
for (unsigned int i = 0; i < size; i++) {
cout << "Employee Id: " << newStaff[i].getID << endl;
cout << "Employee Name: " << newStaff[i].getName << end;
cout << "Employee Salary: " << newStaff[i].getSalary << end;
cout << endl;
}
}
//Employee.h
//Header
#ifndef EMPLOYEE_H
#define EMPLOYEE_H
#include <iostream>
#include <string>
using namespace std;
class Employees{
public:
//after
//Default Constructor
Employees();
//Overload constructor
Employees(int, double, string);
//Destructor
~Employees();
//Accessor Functions
int getID() const;
//getId
//return int - Id for Employee
double getSalary() const;
//getSalary
//return salary - salary of Employee
string getName() const;
//getName
//return name - Name of Employee
//Mutators
void setId(int);
//setId - for Employee
void setSalary(double);
//setSalary - for Employee
void setName(string);
//setName - for Employee
//
//before
//ID
//void setEmployeeId(int a){
//employeeId = a;
//}
////Salary
//void setSalary(double b){
//salary = b;
//}
////Name
//void setName(string c){
//name = c;
//}
private:
//after
//before
int employeeId; //id
double employeeSalary; //salary
string employeeName; //name
};
#endif
//Employees.cpp
#include "Employee.h"
Employees::Employees() {
employeeName = ' ';
}
Employees::Employees(int id, double salary, string name){
employeeId = id;
employeeSalary = salary;
employeeName = name;
}
Employees::~Employees(){
}
int Employees::getID()const{
return employeeId;
}
double Employees::getSalary()const{
return employeeSalary;
}
string Employees::getName()const{
return employeeName;
}
void Employees::setId(int id){
employeeId = id;
}
void Employees::setSalary(double salary){
employeeSalary = salary;
}
void Employees::setName(string name){
employeeName = name;
}
'Employees::getSalary': function call missing argument list;
That seems quite clear: getSalary is a function, and you need an argument list when you call a function:
cout << "Employee Salary: " << newStaff[i].getSalary() << endl;
^^ ^
and similarly for the calls to getID and getName.
Fixing that should also fix the second error; or that might be caused by the mistyping of endl.
I think the error is pretty self explaining, once you know a bit of C++ terms. The second part (use '&Employees::getSalary' to create a pointer to member) will actually confuse you, because the compiler it talking about a totally unrelated C++ capability, that it thinks you may be trying to use.
Let's see:
'Employees::getSalary': function call missing argument list
To call a function, you have to specify the argument list, with parenthesis, even if you have no arguments at all!
cout << "Employee Salary: " << newStaff[i].getSalary() << end;
That is, add a few () here and there.
You have to use function call operator () (application operator) to call a function
function_name() // call a function named function_name
thus:
cout << "Employee Id: " << newStaff[i].getID() << endl;
^^
cout << "Employee Name: " << newStaff[i].getName() << end;
^^
cout << "Employee Salary: " << newStaff[i].getSalary() << end;
^^
This:
newStaff[i].getName
Needs to be this:
newStaff[i].getName()
And so on.