丹生谷森夏 丹生谷森夏 - 9 days ago 5
C++ Question

How can I get a cstring into a class?

I'm going to using cstring finish the program
now I required to get the name of PokemonWorld from user
and initialize it

But I can't get the cstring from main() into class PokemonWorld

I tried

cin >> world.setName
and
cin >> name; world.setName(name)


both of which failed

class PokemonWorld {
private:
char name[10];
public:
void setName(char x[]) {
*name = x;
};
char* getName(){
return name;
};
};

void main() {
PokemonWorld world;
int number;
char name[10];
cout << "What is the World Name ?" ;
cin >> name;

world.setName(name);


Also I cannot using getName to return the name that assigned into PokemonWorld

Here is the error code:

Error C3867 'PokemonWorld::getName': non-standard syntax; use '&' to create a pointer to member

Should I create PokemonWorld as pointer?

Answer

With cstring, you have to use c string manipulator. You definitively can't assign an array to another one. For your issue, use strncpy:

void setName(char x[]) {
    strncpy_s(name, 10, x, 10);
};

Also, to avoid issue, your getter should be:

const char * const getName() const {
    return name;
};

Also, to compare, use strncmp, to concatenate use strncat, ...

Or, because you use c++, use std::string

Comments