storing several strings in an array.

Hello team. just looking for a bit of advice. I want to store a sires of ten names into a single array.i just want to know if i NEED to write the array like this


char studentNames[]= {'J','o','h','n'....}

or if there is a better way to store all the names.
This doesn't work? I believe that you can have arrays of classes, unless I'm wrong. The 'string' class shouldn't be an exception.

1
2
3
4
5
6
std::string name[10];

// Just to test it

name[0] = "bob";
name[1] = "jim";
Last edited on
You can store any data type into an array, especially classes and structs.

You are storing a char array of one name. What you have is correct but storing more than one name into a char array is pretty ridiculous. Just use a string array.


Hardcoding them in at compile time would be like:

string names[10] = {"Bob", "Jon", "Dave",......"Bill"};

You can omit the number if you like but make damn sure that you keep track of how many items you coded in. Accessing items outside of the array result in a nasty thing called a seg fault.

I recommend having the size as a constant and using it whenever you want to loop through the array or check out of bounds.

1
2
3
4
5
6
7
const int MAX_SIZE = 10;

string names[MAX_SIZE] = {"Bob", "Jon", "Dave",......"Bill"};

for (int i = 0; i < MAX_SIZE; i++)
      cout << names[i] << endl;      // print names


The code from doilin will also work.




Last edited on
closed account (zb0S216C)
The downside of not using string literals is that the null-character must be explicitly added to the string. With string literals, however, the null-character is implicitly added for you, making it safer. If not for the null-character, std::cout will print the contents of memory until zero is encountered, which will lead to unexpected results.

Here's the old way :

 
char *strs[3] = {"Str1", "Str2", "Str3"};

Technically, strs isn't an array of strings but an array of pointers to an array of characters. Believe it or not, this complies:

 
std::cout << "String"[0] << std::endl;

One of those things you think is a secret, I suppose. :)

Wazzak
Last edited on
Topic archived. No new replies allowed.