Sunday, July 12, 2009

How can i create an array of names in c++?

i want to store 3 names say john,mac and henry in an array in c++


what code should i write in c++ so as to facilitate this coz i tried doing this


char name[ ]={"john","Mac","Henry"};


this is not working y?????????????


can you plz suggest some possible way to as to get names stored in a array

How can i create an array of names in c++?
You do not need to use string, but if it is easier, you can.





You get an error at the moment, is because "john" it self would be an array of chars. You are trying to create an array of "arrays of chars"





Convert your statement above to


char[3][] = {"john" ... }


You need to add a number somewhere there, whether it be the 3, as in how many names you have, or


char[][6] = {"john" ... }


if you need to know how many chars in the second array. Henry is longest name at 5 chars, you need to add 1 char for a "null character" to end the name.





This is called a multiple array.
Reply:#include%26lt;string.h%26gt;





using namespace std;





void main()


{


string name[]={"john","Mac","Henry"};
Reply:Yes, use strings because otherwise you are dealing with pointers which is something I guess you dont want to do. Here is a possible solution that I just did that you could use if you were using character arrays instead of strings. Bear in mind that c++ is not my strong point so I'm open to correction on this.





#include %26lt;cstdlib%26gt;


#include %26lt;iostream%26gt;





using namespace std;





int main(int argc, char *argv[])


{


char **names = new char*[2];


names[0] = "jack";


names[1] = "jill";





std::cout %26lt;%26lt; "Name 1: " %26lt;%26lt; names[0] %26lt;%26lt; endl;


std::cout %26lt;%26lt; "Name 2: " %26lt;%26lt; names[1] %26lt;%26lt; endl;





system("pause");


return EXIT_SUCCESS;


}
Reply:#include%26lt;string.h%26gt;


#include%26lt;iostream.h%26gt;


void main()


{


char name[]={"john","mac","henry"};


....


...


}


try this way
Reply:char* name[3]={"John","Mac","Henry"};
Reply:Either string.h or char arrays, because C++ don't have string as standard types, try char *name[] instead. in your code I mean.
Reply:Does C++ use strings?If so, shouldnt those be declared as strings and not as chars?


No comments:

Post a Comment