Sorting strings read from standard input, stored in 2D array C++ program example


Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows XP Pro SP2

Header file: Standard

Additional project setting: Set project to be compiled as C++

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C++ Code (/TP)

Other info: none

To do: Sorting strings stored in 2D array in C++ programming

To show: How to sort strings read from standard input, stored in 2D array in C++ programming




// a program will sort a list of a strings entered by the user

#include <iostream>

#include <cstdlib>

#include <cstring>

using namespace std;


int main(void)


// declare two arrays named tname with 1-Dimension and name with 2-Dimension

char tname[20], name[20][20];

// normal variables

int i, j, n;


cout<<"Enter the number of names: ";


// outer loop for counter...

for(i=0; i<n; i++)


cout<<"\nEnter the name(one word) "<<(i+1)<<cin>>name[i];


// inner for loop, read row by row set outer for loop...

for(i=0; i<n-1; i++)

// innermost for loop, read column by column of the characters...

for(j = i+1; j<n>0)


// strcpy()/strcpy_s() - copy the strings...

// compare and swap...

strcpy_s(tname, 20, name[i]);

strcpy_s(name[i], 20, name[j]);

strcpy_s(name[j], 20, tname);


cout<<"\nSorted names:\n";

for (i =0; i<n; i++)



return 0;



Output example:


Enter the number of names: 5

Enter the name(one word) 1: Bush

Enter the name(one word) 2: Blair

Enter the name(one word) 3: Tony

Enter the name(one word) 4: Saddam

Enter the name(one word) 5: Cheney

Sorted names:






Press any key to continue . . .



C and C++ Programming Resources | C & C++ Code Example Index