I wanna know how should I assign a string to a string member of a struct.
for example :
#include<iostream>
#include<string>
using namespace std;
string c="salam";
struct man{
string name;
}*mary;
int main(){
string b ="HI";
(*mary).name=b;
return 0;
}
It doesn't work but I need this kind of assignment. I have string that I do some operations on it and wanna assign it to one of the members of my struct...
Thanks for your help :)
The problem is not with the string; it is with your attempted use of structures. You created a pointer-to-man, not a man.
Here's how to define a type called man, then create an instance of that type called mary, then assign a value to the member of that type called name:
#include <iostream>
#include <string>
using namespace std;
struct man
{
string name;
};
int main()
{
man mary;
mary.name = "HI";
}
Related
Anyone know how to Initialise the array of car registration structures by placing a “Empty” in the car registration number of each array element.
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <conio.h>
#include <iomanip>
using namespace std;
int main()
{
struct car;
{
string car_reg = 0;
char car_manuf[30];
char car_model[30];
double price;
string car_reg{};
}
}
need some h3elp
Explanation inline.
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <conio.h>
#include <iomanip>
using namespace std;
int main()
{
struct car // removed ; the ; terminates the definition, cutting it off
// and leaving you with a declaration. Everything in the braces
// that follow would be seen as a block of code defining two
// automatic variables scoped inside the block. Useless in this
// case.
{
string car_reg = 0; // this is actually NASTY! More on it later
char car_manuf[30] = "EMPTY"; // assigns default value. But only if your
// compiler comes from this decade.
// If you are rocking an antique you can't
// do this. Will cover what you can do below.
char car_model[30] = "EMPTY";
string car_reg{}; // cannot reuse the car_reg identifier in the same scope
// car_reg is either a variable or a function.
}; // ; goes here
car c; // for testing purposes
cout << c.car_manuf << ',' << c.car_model; // for testing
}
string car_reg = 0; is nasty. What it does is defines a member variable car_reg and uses 0 as the default. The 0 is converted to a null pointer to a char array. The string constructor attempts to initialize from a null pointer and blows up at runtime. The compiler is just fine with this bit of stupidity because in the old days NULL could be #define NULL 0 and we don't want to break decades of old code by fixing this problem.
Since we can't do default initializations in pre C++11 code we need a constructor to do the work. Yup. structs can have constructors. This is because a struct and a class are almost identical. The only difference you're ever likely to see between the two is class defaults to private access and structs default to public access.
struct car
{
char car_manuf[30];
char car_model[30];
car (): car_manuf("EMPTY"), car_model("EMPTY")
{
}
};
Note that his isn't as groovy as it looks. You're usually better off with something like
struct car
{
string car_manuf;
string car_model;
car (const string & manuf,
const string & model): car_manuf(manuf), car_model(model)
{
}
};
and not allowing the empty case at all. When possible force users to initialize a class into a fully initialized state. And use std::string. Very handy tool, std::string.
Note that
struct car
{
char car_manuf[30];
char car_model[30];
car (const char * manuf,
const char * model):
car_manuf(manuf), car_model(model) // fails to compile
{
}
};
is not possible. You can't initialize a char array with a pointer to char. I'm not entirely certain why the language doesn't have a rule to handle this, but it doesn't. If forced to use char arrays,
struct car
{
char car_manuf[30];
char car_model[30];
car (const char * manuf,
const char * model)
{
strcpy(car_manuf, manuf);
strcpy(car_model, model);
}
};
and make dang sure that manuf and model will fit in 29 characters or less.
Have you tried a simple for loop, to fill (for example) the char_model array with zeros?
....
char car_model[30];
/* Adding the for loop here (it will fill car_model's elements with zeros*/
for(int i=0; i<=sizeof(car_model); i++){
car_model[i]=0;
....
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <conio.h>
#include <iomanip>
using namespace std;
int main()
{
struct car
{
string car_reg = {"Empty"};
char car_manuf[30];
char car_model[30];
car(const char* manuf,
const char* model)
{
strcpy(car_manuf, manuf);
strcpy(car_model, model);
}
};
}
#include <iostream>
#include <string>
using namespace std;
struct player
{
string name;
int money = 100;
int wins = 0;
};
int main()
{
string user;
cin >> user;
player user;
user.name = user;
}
What is the proper syntax for this in C++? I'm trying to declare the object name as the one given by the user. How would you do this? Would a class be easier to do this? Any tips/advice is much appreciated!
variables names are meaningless at runtime in compiled langages like c++. If you want to refer to a player using his or her provided username at runtime you need a datastructure that will remember the name as as string, like a hashtable or a map (I would recommend a map, those are easier to use) http://www.cplusplus.com/reference/map/map/
best is classes because of security
as by default ,
classes are private in nature but struct are public in nature
#include <iostream>
#include <string>
using namespace std;
class player
{
public:
string name;
int money;
int wins;
public(string name){
this->name = name;
this->money = 100;
this->wins = 0;
}
};
int main()
{
string user;
cin >> user;
player *user = new player(user);
}
I'm a complete c++ beginner.
I'm trying to do a couple things that seem pretty basic: Create an object of a certain class, store it in a vector, then output a value of that object. At the moment it outputs a rectangle character, no matter what character I store.
Here's the code:
#include <iostream>
#include <string>
#include <cstdlib>
#include <conio.h>
#include <time.h>
#include <windows.h>
#include <vector>
#include <algorithm>
#include <map>
using namespace std;
class terrainType
{
public:
string name;
char symbol;
int freq;
terrainType(string,char,int);
};
terrainType::terrainType(string name, char symbol, int freq)
{
name=name;
symbol=symbol;
freq=freq;
}
int main()
{
vector<terrainType> terrainTypes;
terrainType dirt("dirt",'.',1);
terrainTypes.push_back(dirt);
cout << terrainTypes[0].symbol;
return 0;
}
Any advice or background info is appreciated. Thanks!
The three assignments you have in the constructor are effectively no-ops (you're assigning each variable to itself):
terrainType::terrainType(string name, char symbol, int freq)
{
name=name;
symbol=symbol;
freq=freq;
}
The issue is that you have two things called name, and you expect the compiler to figure out that in name=name the left-hand side refers to one of them, whereas the right-hand side refers to the other.
The cleanest way to fix this is by changing to constructor like so:
terrainType::terrainType(string name, char symbol, int freq)
: name(name),
symbol(symbol),
freq(freq)
{
}
The rules of the language are such that this would have the intended meaning.
Another alternative is to avoid using the same identifier to refer to both a member and a function argument:
terrainType::terrainType(string name_, char symbol_, int freq_)
{
name=name_;
symbol=symbol_;
freq=freq_;
}
Yet another alternative is to prefix member access with this->:
terrainType::terrainType(string name, char symbol, int freq)
{
this->name=name;
this->symbol=symbol;
this->freq=freq;
}
I've spent quite a few hours researching and trying to figure out why I'm getting this error. Basically the three files that have to do with the inheriting are CollegeMember.h, Employee.h, and EmpAcademicRecord.h. Employee. is inheriting from CollegeMember.h and EmpAcademicRecord.h is inheriting from Employee.h. Like this CollegeMember <- Employee <- EmpAcademicRecord. The error occurs in EmpAcademicRecord.h. Heres the three files.
CollegeMember.h
#include <cstdlib>
#include <iostream>
#include<ctype.h>
#include<string.h>
#include "Employee.h"
#include "Student.h"
using namespace std;
// ****************************************************************************
// Class Definitions follow
typedef char* String;
// The CollegeMember class
class CollegeMember
{
protected:
int ID_Number;
string FirstName, LastName;
string AddressLine1, AddressLine2, StateProv, Zip;
string Telephone;
string E_Mail;
string answer, answer2, answer3, answer4;//used as sort of booleans for use with validation
// member functions
public:
CollegeMember ( ); // constructor
CollegeMember(const CollegeMember&); //overloaded constructor
void Modify (CollegeMember Member);
void InputData(int x);
string Summary ( ); //summary
string PrintMe(); //fully describes
}; // End of CollegeMember class declaration
Employee.h
#include <cstdlib>
#include <iostream>
#include<ctype.h>
#include<string.h>
#include "EmpAcademicRecord.h"
#include "EmpEmploymentHistory.h"
#include "EmpExtraCurricular.h"
#include "EmpPersonalInfo.h"
#include "EmpPublicationLog.h"
using namespace std;
// ****************************************************************************
// Class Definitions follow
typedef char* String;
// The Employee Class
class Employee: protected CollegeMember
{
float Salary;
protected:
string Department, JobTitle;
// Member Functions
public:
Employee ( ); // constructor
void Modify (Employee ThisEmp);
void InputData(int x);
void SetSalary (float Sal) // Specified as an in-line function
{ Salary = Sal;}
float GetSalary ( ) {return Salary;} // Specified as an in-line function
string Summary ( ); //summary
string PrintMe(); //fully describes
}; // End of Employee class declaration
EmpAcademicRecord.h
#include <iostream>
#include <cstdlib>
#include<ctype.h>
#include<string.h>
using namespace std;
typedef char* String;
class EmpAcademicRecord: protected Employee{ //error occurs on this line
protected:
int ReferenceNumber;
string Institution;
string Award;
string start;
string end;
public:
EmpAcademicRecord();
void InputData (int x);
void Modify(EmpAcademicRecord ThisRec);
void Summary();
};
Any help with this would be greatly appreciated.
That sort of error is usually caused by the type not being defined when you try to use it.
In this case, it appears that you may have included EmpAcademicRecord.h without having first included Employee.h (the includes at the top of the former do not show the latter).
In other words, at the point where the compiler sees:
class EmpAcademicRecord: protected Employee { //error occurs on this line
it has no idea what the Employee class is.
It may be a simple matter of adding:
#include "Employee.h"
to the top of that file, it's a little difficult to be certain since we don't have the code files. In any case, it's certainly a good first step.
Since you have EmpAcademicRecord.h being included by Employee.h, that will probably result in an infinite recursion.
You could fix that with include guards, but I can't see why you need that particulat inclusion. EmpAcademicRecord depends on Employee, not the other way around.
I'm trying to simply use a vector within one of my classes. When trying to access the vector it tells me that it's undefined (but I've defined it in my header).
I have two classes, Person and Dog. A person can own one or more dogs so I want to add each dog a person owns into an array. This should be real simple so this problem is really starting to get to me. Here's some code:
The class Person.cpp:
#include "Person.h"
#include "stdafx.h"
#include <iostream>
using namespace std;
Person::Person(string name, string address, int age)
:name(name),
address(address),
age(age)
{}
int Person::getAge(){
return age;
}
std::string Person::getDogInfo(int index){
}
void Person::addDog(string dogName, string breed){
dogCollection.push_back(Dog(dogName, breed));
}
std::vector<Dog> getDogs(){
return dogCollection; //dogCollection undefined error here
}
And here's Person.h:
#ifndef Person_H
#define Person_H
#include <vector>
#include "Dog.h"
using namespace std;
class Person{
public:
Person(string name, string address, int age);
string getName(){return name};
string getAddress(){return address};
void addDog(string dogName, string breed);
string getDogInfo(int index);
std::vector<Dog> getDogs();
int getAge();
private:
string name;
string address;
int age;
std::vector<Dog> dogCollection;
};
#endif
If you want to have a look at my dog classes I'll paste them as well:
Dog.cpp:
#include "stdafx.h"
#include <iostream>
#include "dog.h"
Dog::Dog(string dogName, string breed)
:dogName(dogName),
breed(breed){}
std::string Dog::Dog.getDogName(){
return dogName;
}
std::string Dog::Dog.getBreed(){
return breed;
}
and Dog.h:
#ifndef Dog_H
#define Dog_H
#include <iostream>
using namespace std;
class Dog{
public:
Dog(std::string dogName, std::string breed);
std::string getDogName();
std::string getBreed();
private:
std::string dogName;
std::string breed;
};
#endif
Also, I just want to add that this is no homework. I'm used to java and I'm only trying to learn some C++ since I need it for future work.
EDIT: Updated the code
std::vector<Dog> dogCollection; // here im defining dogCollection, no error here!
There actually is an problem here - class Dog isn't known to the compiler at this point.
You can solve this by either including Dog.h before Person.h in Person.cpp, or better add an #include "Dog.h" at the top of Person.h.
This is incorrect (and unrequired):
dogCollection = new std::vector<Dog>; // Remove this line.
as dogCollection is not a std::vector<Dog>*.
This is also incorrect:
void Person::addDog(string dogName, string breed){
Dog *newDog = new Dog(dogName, breed);
dogCollection.push_back(newDog);
}
as dogCollection contains Dog instances, not Dog*. Change to:
void Person::addDog(string dogName, string breed){
dogCollection.push_back(Dog(dogName, breed));
}
There is a problem with all of constructors:
Person::Person(string name, string address, int age){
name=name;
address=address;
age=age;
}
This is assigning the argument name to itself: it is not assigning to the member name. Same for address and age and similarly for the constructors of the other classes. Use initializer list:
Person::Person(string name, string address, int age) :
name(name),
address(address),
age(age)
{}
This method does not return a std::string:
string Person::getDogInfo(int index){
}
EDIT:
Missing class qualifier:
std::vector<Dog> getDogs(){
return dogCollection; //dogCollection undefined error here
}
means this is just a free function, with no association to class Person and therefore no access to dogCollection.
Change to:
std::vector<Dog> Person::getDogs(){
return dogCollection;
}
There are several problems with your code, and most of the other answers have pointed them out - mostly regarding the use of new when it should not be used. (Are you a C# programmer, moving to C++?)
However, there are problems with the #include directives as well. As #Bo mentioned, since Person uses Dog, you should include that header in Person.h. But Person also uses vector so that header should be included there as well. So Person.h should start with...
#include <vector>
#include "Dog.h"
Then in Person.cpp you don't have to include those files.
As a general rule (you can learn about "forward declaration" later), any types referenced in a header should be #included in that header.