char input help

Removed.
Last edited on
return name[30];
This is attempting to return the 31st element of the array name. No such element exists. name[30] means "the 31st element of the array name".

1
2
3
4
void Animal::setName(char n)
{
	name[30] = n;
}

You're passing in a char. One single char. Just one. Then, you attempt to write that single char into the 31st element of the array. No such element exists.

It looks like you just don't understand how to use arrays. It's a shame you've been told to use a char array instead of a string. char arrays are for intermediate users; not beginners. Beginners should be using string.

char name = 0; This creates a single char. Just one. So when you do this a few lines later:
cin >> name;
You're trying to store whatever you type in into a single char. Just one char. So you get just one char from the input.


Here is how to fetch many letters from the input:

1
2
char array[30];
cin >> array;


Note that the array can only store 30 in this case. Playing with char arrays is dangerous.

If you want to copy a char array into another char array, you need to copy each char. There are functions to help you do this:

1
2
3
4
void Animal::setName(char* the_array_containing_the_name)
{
  strcpy(name, the_array_containing_the_name); // copy chars
}

strcpy is dangerous. Read about it first.

So the constructor makes no sense. Passing in a single char?
1
2
3
4
5
Animal::Animal(char n, int a)
{
	name[30] = n;
	age = a;
}


This should be enough information for you to understand the fundamental flaws in what you've done.
Topic archived. No new replies allowed.