What is the error in sorting names and tolower function?
1. I wonder whats the problem. Has no error and warning.. but can not sort names. Why? Whats the mistake(s)? "red color"
2. why if i use tolower the character.. got problem...whats the problem? "blue color"
thank you in advance...
#include
#include
using namespace std;
int main()
{
string *name;
string temp;
int num;
/* ********Enter number of students*********** */
cout << "Please enter the numbers of student: ";
cin >> num;
name = new string [num];
/* *********Sorting names by alphabet************* */
for (int i=0; i < num; i++)
{
cout << "Enter student name [" << i+1 << "]: ";
getline(cin,name[i]);
name[i] = tolower(name[i]);
}
for (int pass=0; pass <3; pass++)
for (int i=0; i <3; i++)
if ( name[i] > name[i+1] )
{
temp = name[i];
name[i] = name[i+1];
name[i+1] = temp;
}
for (int a=0; a < num ; a++)
cout << name[a] << endl;
cout << "\nList of student :\n";
for ( i = 0; i < num; i++ )
cout << name[i] << endl;
/* ********* Listing names that contain "Mo "************ */
cout << "\nList of student name that contains the string Mo:\n";
for ( int b= 0; b < num; b++ )
{
if ( name[b].find( "mo" ) == 0 )
cout << name[b] << endl;
}
delete [] name;
return 0;
}
koh
Junior Poster in Training
73 posts since Jul 2004
Reputation Points: 11
Solved Threads: 0
name[i] = tolower(name[i]);
The functiontolower operates on a single character, not a std::string.
for ( int pass=0; pass <3; pass++ )
for ( int i=0; i <3; i++ )
if ( name[i] > name[i+1] )
{
temp = name[i];
name[i] = name[i+1];
name[i+1] = temp;
}
If i is 2, then i + 1 is 3, which is off the end of the array.
Dave Sinkula
long time no c
5,058 posts since Apr 2004
Reputation Points: 2,780
Solved Threads: 314
koh
Junior Poster in Training
73 posts since Jul 2004
Reputation Points: 11
Solved Threads: 0