String Array C++ – Implementation with an example
If you haven’t learned about arrays or strings before, then read up on string array c++ first before proceeding to read this.
Two-dimensional arrays can be used to create string array c++. The way they work is the following
- Create a 2D character array
- The left array determines the number of strings
- The right array specifies the maximum length of each string, which also includes the null terminator
For example, the following declares an array of 40 strings, each having a maximum length of 69 characters, plus the null terminator.
char str_array[40][70]
You can access each individual string by specifying only the left index. Using the gets() function, we can call the 2nd string in the str_array;
gets(str_array[1]);
To access an individual character within the second string which will display the fourth character of the 2nd string, you can use the statement:
cout << str_array[2][3];
The example code below shows string array c++ being applied by creating a simple student database. The two-dimensional array of numbers holds pairs of names and student numbers. To find a number, you enter the name which the student number displayed.
// A Student database applying array of strings #include <iostream> #include <cstdio> using namespace std; int main() { int i; char str[70]; // Read string entered in // Create a list of 40 strings with a maximum of 69 characters char numbers[40][70] = { "Sahil", "s3432952", "David", "s5656564", "Aaron", "s4962768", "Cletus", "s223564", "Mohamaad", "s3489112", }; // Main Menu cout << "Enter name:"; cin >> str; // Search and match for the correct name for (i = 0; i < 40; i = i + 2) if (!strcmp(str, numbers[i])) { // Display student number cout << "Number is " << numbers[i + 1] << "\n"; break; } if (i == 40) cout << "Not found\n"; return 0; }