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.
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.
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
constint 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 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. :)