Wednesday, November 5, 2014

C++ program that arranges names alphabetically

#include<iostream>
#include<string>
using namespace std;

int main()
{
int N;
string ch1[50],
  temp;
cout << "Enter the number of names to be arranged(should be less than 50): ";
cin >> N;
/* using cin >>  and then calling cin.get causes problems because
the >> operator leaves the newline character in the keyboard buffer. When the cin.get function executes,
the first character it sees in the keyboard buffer is the newline character, so it reads no further.
The same problem exists when a program uses cin >> and then calls cin.getline to read a line of input!!! */
//so cin.igbore is used...
cin.ignore();
cout << "Enter the names:";
for( int i=0 ; i<N ; i++ )
{
//cin >> ch1[i];
cout << "\nEnter Name "
<< (i+1)
<< ": ";
getline(cin,ch1[i]);
}
//for manipulation...
for( int i=0 ; i<(N-1) ; i++ )
{
for( int j=i+1 ; j<N ; j++ )
{
if(ch1[j]<ch1[i])
//if(strcmp(ch1[j],ch1[i])
{
temp = ch1[i];
ch1[i] = ch1[j];
ch1[j] = temp;
}


}
}
cout << "\nThe Names arranged in Ascending order are:\n";
for( int i=0 ; i<N ; i++ )
{
cout << "Name "
<< (i+1)
<< ": "
<< ch1[i]<<endl;
}

return 0;
}

No comments:

Post a Comment