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

  1. Create a 2D character array
  2. The left array determines the number of strings
  3. 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 &lt;iostream&gt;
#include &lt;cstdio&gt;

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 &lt;&lt; "Enter name:";

cin &gt;&gt; str;

// Search and match for the correct name
for (i = 0; i &lt; 40; i = i + 2)
if (!strcmp(str, numbers[i]))
{
// Display student number
cout &lt;&lt; "Number is " &lt;&lt; numbers[i + 1] &lt;&lt; "\n";
break;
}

if (i == 40)
cout &lt;&lt; "Not found\n";

return 0;
}
Share this post

FAQ's

What are arrays?

Arrays in C++ and other languages is a collection of elements of the same variable type that are placed in contiguous memory locations that can be individually referenced. The way it can be individually referenced is by adding an index to the identifier.

What are strings?

Strings are used for storing text in programming in variables which can be reused in different areas of the code

What are Two-dimensional arrays?

Two dimensional arrays is an array within array that can be pictured as a grid that be created by declaring a two dimensional array.

How to apply an array of strings in C++?

Two-dimensional arrays can be used to create string array c++. The way they work is the following

  1. Create a 2D character array
  2. The left array determines the number of strings
  3. The right array specifies the maximum length of each string, which also includes the null terminator