-
String arrays
Hi all,
I am pretty new to c++ programming but fairly good at VB.
My question is this:-
I want to create an array of strings such that
string[1]="sheep"
string[2]="cows "
string[3]="pigs " etc etc...(which is easy in VB)
The problem is that strings themselves are treated as character arrays in c++
so I need a 2 dimensional array, eg. animals[10][10]
the problem is I can declare the array, but then I cannot get it to accept any input as strings for example...
animals[5][5]="A" works and puts the character "A" at 5,5 but
animals[5][5]="pigs " does not, neither does
animals[][5]="pigs " or
animals[5][]="pigs ".
is there any way of assigning strings directly to arrays like this or will I have to start using pointers?
Thanks in anticipation
by the way, this is not homework, I am 42 years old!
-
you'll need to include string.h
and use strcpy
eg
strcpy(animal[5], " pigs ");
would copy pgs into animal[5] which is a char ptr
and btw i'm 19
-
To initialise a character string array, (I'm assuming that's what you want), use this construction...
char array[10][10] = {"horse", "pig"};
cout << array[0]<<" "<<array[1]<<endl;
-
Create and initialize an array of character pointers as follows:
char* cpArray[3] = { "sheep", "cows", "pigs" };
Doing this will give you:
cpArray[0] equal to "sheep"
cpArray[1] equal to "cows"
cpArray[2] equal to "pigs"
-
If you're using C++, you might want to use the string class, because then you don't need to worry about string lengths.
Code:
#include <iostream>
#include <string>
int main()
{
string animal[5];
animal[0] = "pig";
animal[1] = "cows";
animal[2] = "sheep";
animal[3] = "horse";
animal[4] = "4/2/3 legged creature";
cout << "Animals:\n";
cout << animal[0] << ", " << animal[1] << ", "
<< animal[2] << ", " << animal[3] << ", and "
<< animal[4] << ".\n";
return 0;
}
-
Thanks.
Thank everybody, you've been a great help.
The copying using strcpy() 'sort of' worked but gave a system error message (I think I tried to put too many characters into my array:o
The creation of an array of pointers worked well (thanks unregistered) and will give me what I needed.
I was intrigued by the string class thingie(robwhit), although this didn't work as it was written, it came up with an undeclared variable 'string' error, I think this was because the string class had not yet been defined and I intend to go away and read up about classes.
Thanks again
-
Robwhit's example omits the line...
using namespace std;
... after the includes.