I am new in programming and i wanted to know how can I input data from keyboard from class. Anyone?
#include <iostream>
#include <string>
using namespace std;
class Human{
private:
string *name;
int *age;
public:
Human(string iname, int iage){
name = new string;
age = new int;
*name = iname;
*age = iage;
}
void display(){
cout << "Hi I am " << *name << " and I am " << *age << " years old" << endl;
}
~Human(){
delete name;
delete age;
cout << "Destructor!";
}
void input(string, int)
{
string name;
int age;
cout << "Name: "; cin >> name;
cout << "Age: "; cin >> age;
}
};
int main()
{
Human *d1 = new Human(Human::input(?????????????????));
d1->display();
delete d1;
return 0;
}
EDIT:
I understand what I can do this:
int main()
{
Human *d1 = new Human("David",24);
d1->display();
return 0;
}
And this:
int main()
{
string name;
int age;
cout << "Name: "; cin >> name;
cout << "Age: "; cin >> age;
Human *d1 = new Human(name,age);
d1->display();
return 0;
}
But I want to know how can I put the data from keyboard with an input function.
Zygis you need to read a tutorial for the basics in C++. Pointers, the *, is a powerful thing programmers can use, but only when they need to. In this case, you do not need to. When do you need them? I think you should leave that for later and focus on my example below. When you understand that, you can read about Pointers in the internet.
#include <iostream>
#include <string>
using namespace std;
class Human {
private:
// data members of class
string name;
int age;
public:
// constructor without arguments
// useful for initializing the data members
// by an input function
Human() {
name = ""; // empty string
age = -1; // "empty" age
}
// constructor with arguments
// useful when you know the values
// of your arguments
Human(string arg_name, int arg_age) {
name = arg_name;
age = arg_age;
}
void display() {
cout << "Hi I am " << name << " and I am " << age << " years old"
<< endl;
}
// the data members will go out of scope automatically
// since we haven't used new anywhere
~Human() {
cout << "Destructor, but the default one would be OK too!\n";
}
// prompt the user to giving values for name and age
void input() {
cout << "Please input name: ";
cin >> name;
cout << "Please input age: ";
cin >> age;
}
};
int main() {
// Let the user initialize the human
Human human_obj_i;
human_obj_i.input();
human_obj_i.display();
cout << "Now I am going to auto-initialize a human\n";
// Let the program itseld initialize the human
Human human_obj("Samaras", 23);
human_obj.display();
return 0;
}
Example run:
Please input name: Foo
Please input age: 4
Hi I am Foo and I am 4 years old
Now I am going to auto-initialize a human
Hi I am Samaras and I am 23 years old
Destructor, but the default one would be OK too!
Destructor, but the default one would be OK too!
Hope that helps! ;)
Related
i got confused about the structure when i need to to pass the value in a function
#include <iostream>
using namespace std;
struct student
{
int studentID;
char studentName[30];
char nickname[10];
};
void read_student(struct student *);
void display_student(struct student *);
int main()
{
student *s;
//struct student *ps;
read_student(s);
display_student(s);
}
void read_student(struct student *ps)
{
int i;
for (i = 0; i <= 2; i++)
{
cout << "Enter the studentID : ";
cin >> ps->studentID;
cout << "Enter the full name :";
cin.ignore();
cin >> ps->studentName;
cout << "Enter the nickname : ";
cin.ignore();
cin >> ps->nickname;
cout << endl;
}
}
void display_student(struct student *ps)
{
int i;
cout << "student details :" << endl;
for (i = 0; i <= 2; i++)
{
cout << "student name : " << *ps ->studentName << " (" << &ps ->studentID << ")" << endl;
ps++;
}
}
its only problem at the variable at line 19 and when i try to edit it will became more problem
student *s;
//struct student *ps;
//struct student *ps;
read_student(s);
display_student(s);
also can someone explain how to transfer pointer value of structure to the function and return it back to the main function
You are suffering from some leftovers from your C-Language time. And, you have still not understood, how pointer work.
A pointer (as its name says) points to something. In your main, you define a student pointer. But it is not initialized. It points to somewhere. If you read data from somewhere, then it is undefined behavior. For writing, it is the same, plus that the system will most likely crash.
So, define a student. And if you want to give it to a sub-function, take its address with th &-operator (this address will point to the student) and then it will work.
You need also to learn abaout dereferencing. Your output statement is wrong.
Last but not least, if you want to store 3 students, then you need an array or some other storage where to put them . . .
In your read function you always overwrite the previously read student and in your display function you show undetermined data.
Please have a look at your minimal corrected code:
#include <iostream>
using namespace std;
struct student
{
int studentID;
char studentName[30];
char nickname[10];
};
void read_student( student*);
void display_student( student*);
int main()
{
student s;
//struct student *ps;
read_student(&s);
display_student(&s);
}
void read_student( student* ps)
{
cout << "Enter the studentID : ";
cin >> ps->studentID;
cout << "Enter the full name :";
cin.ignore();
cin >> ps->studentName;
cout << "Enter the nickname : ";
cin.ignore();
cin >> ps->nickname;
cout << endl;
}
void display_student( student* ps)
{
cout << "student details :" << endl;
cout << "student name : " << ps->studentName << " (" << ps->studentID << ")" << endl;
ps++;
}
And, the commenters are right. You must read a book.
I tried this code but when I am calling the member function inside the loop it is giving the garbage value of the details and when I am calling the member function outside the loop it is giving me error.
#include<iostream>
#include<string.h>
using namespace std;
class student
{
char name[10];
int id,rollno;
public:
student(char name[10],int id,int rollno)
{
strcpy(this->name,name);
this->id=id;
this->rollno=rollno;
cout<<"the name of the student is:"<<name<<endl;
cout<<"the id of the student is:"<<id<<endl;
cout<<"the roll no of the student is:"<<rollno<<endl;
}
};
int main()
{
int id1,rollno1;
char name1[10];
for(int i=1;i<=2;i++)
{
cout<<" enter the detail of the student "<<i<<" "<<endl;
cout<<"enter the name of the student:";
cin>>name1;
cout<<"enter the id of the student:";
cin>>id1;
cout<<"enter the roll no of the student:";
cin>>rollno1;
student d[]={student(name1,id1,rollno1)};
d[i].print();
}
return 0;
}
Here's your code review.
#include <iostream>
#include <string.h>
using namespace std; // it is strongly suggested that you don't use the whole header unless your intent is speeding up coding
class Student // capitalize classes
{
char _name[10];// it is ok, however, if you use the <string> header, why would you go back to char type?
int _id, _rollno;
public:
Student(char name[10] /* this is just the array's first item passed! */, int id, int rollno)
{
// Don't use this->, use an underscore for one of the names.
// I use underscores for the encapsulated data
strncpy_s(_name, name, 9);// a safer version
_id = id;
_rollno = rollno;
cout << "\nCtor says: ";
cout << "the name of the student is: " << _name << endl;
cout << "the id of the student is: " << _id << endl;
cout << "the roll no of the student is: " << _rollno << endl;
cout << '\n';
}
const char* getName() { return _name; }
const int getId() { return _id; }
const int getRollNo() { return _rollno; }
// unless you overload operator<< , you have to make getters for your info, or make it public
};
int main()
{
int id, rollno;// why 1? they won't intersect with the function
char name[10];
Student *s[2];//you must make that on the heap; otherwise you need a default constructor
for (int i{ 0 }; i < 2; i++)// start with 0 and make it just <
{
cout << "enter the details of the student " << i << endl;// Why so many spaces?
cout << "enter the name of the student: "; // add space after the colon
cin >> name;// remember, you're limited to 9 chars + \n !!!
cout << "enter the id of the student: ";
cin >> id;
cout << "enter the roll no of the student: ";
cin >> rollno;
//student d[] = { student(name,id,rollno) }; // you can't do this. It's not flexible.
// You either assign enough space for the intended number of students in the stack, statically, or
// you lett it find more space in the heap = dynamically
//this goes to the heap
s[i]= new Student( name,id,rollno );// parentheses are well
//s[i] = new Student{ name,id,rollno };// initializer list may also do
//d[i].print();// what's to print here? It's not POD, cout needs instructions
cout << "Stored data -> Id: " <<
s[i]->getId() << ", Name: " // -> dereferences the pointer, and s is a pointer now
<< s[i]->getName() << ", Roll no: "
// or you can dereference it
<< (*s[i]).getRollNo()
<< endl << endl; // make some extra space here
}
return 0;
}
#include <iostream>
#include <cstring>
using namespace std;
class Film {
private:
string name;
int year_prod;
string producer;
string main_actor;
public:
Film();
void print()
{
cout << "\nThe name of movie: " << name;
cout << "\nThe year of produced: " << year_prod;
cout << "\nProducer: " << producer;
cout << "\nMain actor: " << main_actor << endl;
}
void SetName(string xName)
{
name = xName;
}
string GetName()
{
return name;
}
void SetYearP(int xYearP)
{
year_prod = xYearP;
}
int GetYearP()
{
return year_prod;
}
void SetProducer(string xProducer)
{
producer = xProducer;
}
string GetProducer()
{
return producer;
}
void SetMaina(string xMaina)
{
main_actor = xMaina;
}
string GetMaina()
{
return main_actor;
}
};
int main()
{
Film obs[100]; // maximum of 100 hundred films
int n;
cout << "how many films ";
cin >> n;
for (int i = 0; i < n; ++i)
{
string name;
int year;
string prod;
string actor;
cout << "enter the film name ";
cin >> name;
cout << "enter the production year ";
cin >> year;
cout << "enter the producer name ";
cin >> prod;
cout << "enter the actor name ";
cin >> actor;
obs[i].SetName(name);
obs[i].SetYearP(year);
obs[i].SetProducer(prod);
obs[i].SetMaina(actor);
}
}
I've done half of my code but I get errors while compiling saying: unresolved external symbol "public: __thiscall Film::Film(void)" (??0Film##QAE#XZ) referenced in function _main AND 1 unresolved externals. I'm not sure if I had in the correct way objects of n Film from user input because I'm still a beginner in OOP.
You didn't implement your constructor:
public:
Film();//<-- declared, but not defined.
If you don't want your constructor to do anything, just add an empty body:
public:
Film() {};
or even better, explicitly declare it as the default-constructor:
public:
Film()=default;
Please try this out. Hope this helps.
class Film {
...
...
...
public:
//Film(); Remove this line if you are not defining Film()
void print()
{
cout << "\nThe name of movie: " << name;
cout << "\nThe year of produced: " << year_prod;
cout << "\nProducer: " << producer;
cout << "\nMain actor: " << main_actor << endl;
}
...
...
...
}
If you want it to be a default constructor add an empty block Film(){}
You have to implement the constructor for your class. The constructor is the method that create an instance of the class. The set functions have the purpose to modify the attributes of an object, but the initialization of the attributes must be done in the constructor.
For example:
public:
//default constructor: it does not take
//anything as input, it sets name as an
//empty string and the year to 1900
Film(){
name = "";
year = 1900;
}
// It creates a Film object, whose name
// is NAME and whose year is YEAR
Film(string NAME, int YEAR){
name = NAME;
year = YEAR;
}
// set function which allows to modify the
// year of a Film object.
void setYear(int newYear){
year = newYear;
}
Have a look here for a quick introduction.
EDIT: you may want to set the default constructor as
Film(){};
In this way you have to invoke all the set functions to initialise its attributes.
How could I use <vector> for an array of objects, which need to be given value through constructors? e.g class with name,age would need to get in an array with information given through constructor Student(string n, int a ) { name = n , age = a } .
All the data will be given through keyboard..
Here is an example code of a program capable of getting and storing the name and the age of a list of students using vectors. After that, it prints the information stored. I am using MSVC as the compiler, so if you are not on windows, you can remove system("pause"):
#include <vector>
#include <string>
#include <iostream>
using namespace std;
class Student {
public:
Student(string n, int a) : name(n), age(a) {}
string GetName(void) { return name; }
int GetAge(void) { return age; }
private:
string name;
int age;
};
int main(void) {
vector<Student> students;
unsigned int n;
cout << "How many students are there?" << endl;
cin >> n;
for (unsigned int i = 0; i < n; ++i) {
string name;
int age;
cout << endl << "Please give me the information of the student " << i + 1 << endl;
cout << "What is the name of the student?" << endl;
cin >> name;
cout << "What is the age of the student?" << endl;
cin >> age;
students.push_back(Student(name, age));
}
cout << endl << "Printing information of the students" << endl << endl;
for (unsigned int i = 0; i < n; ++i) {
Student& student = students[i];
cout << "Student " << i + 1 << " is " << student.GetName() << " and is " << student.GetAge() << " years old." << endl;
}
system("pause");
return 0;
}
One can use an initializer-list to directly construct a vector of students:
std::vector<Student> students{
{ "John", 22 },
{ "Melissa", 19 }
};
To add a student later one could use member function emplace_back() which just forwards its arguments to the Student constructor:
students.emplace_back( "Andy", 23 );
Pre C++11 one would have to use member function push_back() instead:
students.push_back( Student( "Andy", 23 ) );
More usage examples can be found on the linked reference pages.
I'm not really sure if the title is correct but i have the following piece of code:
#include <iostream>
#include <string>
using namespace std;
class department
{
private:
string name;
int budget;
public:
int NoT; //Number of teachers
int NoS; //Number of students
void setName(string nam);
void setBudget(int budg);
int getBudget ();
string getName();
};
class school
{
private:
int YoE;
string name;
public:
department *dpt;
int NoDpts;
school();
};
void department::setName(string nam)
{
name=nam;
}
void department::setBudget(int budg)
{
budget=budg;
}
int department::getBudget()
{
return budget;
}
string department::getName()
{
return name;
}
school::school()
{
YoE=2000; // Year of estabilishment
name="Somename";
NoDpts=37;
}
int main()
{
string name;
int budget;
int budg;
school *sch;
sch=new school;
if (!sch)
throw("Out of memory");
sch->dpt=new department[37];
if (!sch->dpt)
throw("Out of memory");
for (int i=0;i<sch->NoDpts;i++)
{
cout << "Insert name for department#" << i+1 << ": ";
cin >> name;
sch->dpt->setName(name);
cout << "Insert budget for department " << name << ": ";
cin >> budget;
sch->dpt->setBudget(budget);
cin.ignore();
}
cout << "Insert a budget for school: ";
cin >> budget;
for (int i=0;i<sch->NoDpts;i++)
{
if (budg=sch->dpt->getBudget()>=budget)
{
cout << "Name of department is: " << sch->dpt->getName() << endl;
cout << "Budget of department amounts to: " << sch->dpt->getBudget() << endl;
cout << endl;
}
}
return 0;
}
As you can see, i allocated 37 departments, however i don't know how to access them.I mean that in the following line:
sch->dpt->setName(name);
I merely access the name of the first department (indirectly by using an accessor function),thus overwriting it and getting different results than expected.This happens to other members too such as
sch->dpt->setBudget(budget);
So i am simply asking how i can access the members of the rest of the departments.