Hi i have a question about inputting to char*.

For instance,i have made a class "Name",and am passing my constructors in as follows

Name* n1 = new Name("Nelly the elephant");
Name::Name(char* name){
    this->name = name;
}

But i am confused as to how i would code my addName().Ideally i would like to add a name into a char* variable and copy it to my Class Name attribute that holds the name but i am confused on the following with char*:

If i begin to enter into a char*,how can i stop entering do i have an unlimited amount of space?

Ideally i would like to stay away from the use of strings and inputting via a for loop.

Thank you for any help.

Recommended Answers

All 4 Replies

if this->name is a pointer (i.e. char*) then you have to allocate space for it before copying the string. Just setting with = as in your example will not work.

Name::Name(char* nm){
    this->name = new char[strlen(nm)+1);
    strcpy(this->name,nm);
}

>>Ideally i would like to stay away from the use of strings and inputting via a for loop.
Why? Just for grins, then ok it might be a learning experience. But in practice, programs don't waste their time using a loop like that.

If you want to input the name via cin then you will have to set some sort of limit so that the program doesn't get data overflow

void addName()
{
   const int MAXNAMELEN = 80;
    this->name = new char[MAXNAMELEN];
    cin.getline( this->name, MAXNAMELEN);
}

if this->name is a pointer (i.e. char*) then you have to allocate space for it before copying the string. Just setting with = as in your example will not work.

Name::Name(char* nm){
    this->name = new char[strlen(nm)+1);
    strcpy(this->name,nm);
}

end quote.

Thanks for the reply, I can see what you mean by the code above,but for some reason my program does allow me to do that,would this lead to memory leaks or problems further down the line?

I think you misunderstood what I meant aswell, I want to stay away from the use of loops also,sorry I didn't make that clear!

void addName()
{
   const int MAXNAMELEN = 80;
    this->name = new char[MAXNAMELEN];
    cin.getline( this->name, MAXNAMELEN);
}

Is the code above would be a standard method of entering information to a char*, using the getline function?

getline() will permit you to enter spaces in the string. If you don't want the spaces then use >> operator cin >> this->name; , but the problem with that is the >> operator will allow you to enter more characters than what this->name can hold.

>>would this lead to memory leaks or problems further down the line?
Probably if you fail to delete[] the memory.

In c++ it is better to use std::string instead of char* because you don't have to bother with memory allocation; the class will allocate memory as necessary.

cheers dragon

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.