sorting char array

R

richardha241

I have problem sorting an array of books with variable char. Let assume I put three names in instead of books. The names Bill Clinton, George Bush, and Hillary Johnson. After the sort with my codes, the array is emptied. What is wrong? How do I sort with char array type instead of string? Here are the codes:

#include <cstdlib>
#include <iostream>
#include <iomanip>
//#include "mainMenu.h"
#include <string>

using namespace std;


void lookUpBook(char[][51]);
void addBook(char[][51]);


const int arrSize=20;
char bookTitle[arrSize][51];


int main(int argc, char *argv[])
{


addBook(bookTitle);
lookUpBook(bookTitle);
system("PAUSE");
return 0;
}

void lookUpBook(char bookTitle[][51]) //stub function
{
//char searchBook[51];
char searchBook[51];
cout<<"Enter book title to be searched:";
cin.getline(searchBook,51);

int startScan, minIndex;
char minValue[51];
for (startScan =0; startScan < arrSize-1; startScan++)
{
strcpy(bookTitle[startScan],minValue);
minIndex= startScan;
for (int index = startScan+1; index < arrSize; index++)
{
if (strcmp(bookTitle[index],minValue)<0)
{
strcpy(minValue,bookTitle[index]);
minIndex=index;
}
}
strcpy(bookTitle[minIndex],bookTitle[startScan]);
strcpy(bookTitle[startScan],minValue);
}


//display book titile array to see if the array sorted correctly
cout<<"The sorted book title are: "<<endl;
for (int count = 0; count < arrSize; count++)
cout<<"Book "<<count+1<<": "<<bookTitle[count]<<endl;
// starting binary search

int first =0, last=arrSize-1, middle, position=-1;
bool found = false;
while (!found && first <= last)
{
middle= (first+last)/2;
if (strcmp(bookTitle[middle],searchBook)==0)
{
found = true;
position=middle;
}
else if (strcmp(bookTitle[middle],searchBook)>0)
last=middle-1;
else
first=middle+1;
}
if (position==-1)
cout<<"The book does not exist in inventory.\n\n";
else
cout<<"The book is found record "<<position<<". \n\n";

}
void addBook(char bookTitle[][51])
{
char choice;
for (int count =0; count < arrSize; count++)
{
if (strcmp(bookTitle[count],"")==0) // if (bookTible[count]=="") won't work, got to use the comparing string function strcmp
{
cout<<"Enter the title of the book: ";
cin.getline(bookTitle[count],51);
cout<<"Do you want to enter another book? (Y/N):";
cin>>choice;
cin.ignore();
if (choice =='Y' || choice =='y');
else
break;
}
else if(bookTitle[arrSize-1]!="")
{
cout<<"No more book may be added to inventory.\n";
}
}
for (int count2=0; count2<arrSize; count2++)
cout<<"Book "<<count2+1<<": "<<bookTitle[count2]<<endl;

}
 
S

Stefan Ram

How do I sort with char array type instead of string?

#include <iostream>
#include <ostream>
#include <algorithm>
#include <iterator>
#include <string>
#include <initializer_list>

int main()
{ char const * a[] =
{ "omicron", "pi", "phi", "chi", "epsilon", "rho", "sigma", "tau", "upsilon",
"nu", "xi", "zeta", "gamma", "eta", "theta", "psi", "omega", "alpha",
"beta", "delta", "iota", "kappa", "lambda", "mu", };
::std::sort
( ::std::begin( a ), ::std::end( a ),
[]( const std::string &l, const std::string &r )->bool
{ return !( r < l ); } );
::std::copy
( ::std::begin( a ), ::std::end( a ),
::std::eek:stream_iterator< ::std::string >( ::std::cout, "\n" )); }
 
S

Stefan Ram

How do I sort with char array type instead of string?
{ char const * a[] =

#include <iostream>
#include <ostream>
#include <algorithm>
#include <iterator>
#include <string>
#include <cstring>
#include <initializer_list>

void swap( char a[ 51 ], char b[ 51 ])
{ for( int i = 0; i < 51; ++i )
{ char const tmp = a[ i ]; a[ i ] = b[ i ]; b[ i ]= tmp; }}

void sort( char a[][ 51 ], size_t const z )
{ bool swapped; do
{ swapped = false;
for( size_t i = 1; i < z; ++i )
{ if( strncmp( a[ i - 1 ], a[ i ], 50 )> 0 )
{ swap( a[ i - 1 ], a[ i ] ); swapped = true; }}}
while( swapped ); }

int main()
{ char a[][ 51 ]=
{ "omicron ",
"pi ",
"phi ",
"chi ",
"epsilon ",
"rho ",
"sigma ",
"tau ",
"upsilon ",
"nu ",
"xi ",
"zeta ",
"gamma ",
"eta ",
"theta ",
"psi ",
"omega ",
"alpha ",
"beta ",
"delta ",
"iota ",
"kappa ",
"lambda ",
"mu ", };
sort( a, sizeof a / sizeof 0[ a ]);
::std::copy( ::std::begin( a ), ::std::end( a ),
::std::eek:stream_iterator< ::std::string >( ::std::cout, "\n" )); }
 
S

Stefan Ram

[email protected] (Stefan Ram) said:
How do I sort with char array type instead of string?
{ char const * a[] =
{ char a[][ 51 ]=

#include <iostream>
#include <ostream>
#include <algorithm>
#include <iterator>
#include <string>
#include <cstring>
#include <initializer_list>
#include <stdlib.h>

int compare( const void * a, const void * b )
{ return ::std::strcmp
( static_cast< char const * >( a ), static_cast< char const * >( b )); }

int main()
{ char a[][ 51 ]=
{ "omicron ",
"pi ",
"phi ",
"chi ",
"epsilon ",
"rho ",
"sigma ",
"tau ",
"upsilon ",
"nu ",
"xi ",
"zeta ",
"gamma ",
"eta ",
"theta ",
"psi ",
"omega ",
"alpha ",
"beta ",
"delta ",
"iota ",
"kappa ",
"lambda ",
"mu ", };
::std::qsort( a, sizeof a / sizeof 0[ a ], 51, compare );
::std::copy( ::std::begin( a ), ::std::end( a ),
::std::eek:stream_iterator< ::std::string >( ::std::cout, "\n" )); }
 
I

Ian Collins

Stefan said:
How do I sort with char array type instead of string?

#include <iostream>
#include <ostream>
#include <algorithm>
#include <iterator>
#include <string>
#include <initializer_list>

int main()
{ char const * a[] =
{ "omicron", "pi", "phi", "chi", "epsilon", "rho", "sigma", "tau", "upsilon",
"nu", "xi", "zeta", "gamma", "eta", "theta", "psi", "omega", "alpha",
"beta", "delta", "iota", "kappa", "lambda", "mu", };
::std::sort
( ::std::begin( a ), ::std::end( a ),
[]( const std::string &l, const std::string &r )->bool
{ return !( r < l ); } );
::std::copy
( ::std::begin( a ), ::std::end( a ),
::std::eek:stream_iterator< ::std::string >( ::std::cout, "\n" )); }

While the example is sound, this is one case where the unnecessary
"::std" adds nothing more than visual clutter.
 
S

Stefan Ram

Ian Collins said:
While the example is sound, this is one case where the unnecessary
"::std" adds nothing more than visual clutter.

Without »::std«, the text »::std::sort« would be »::sort«,
which wouldn't work. ADL would allow »sort« alone here, but
when I am full-text searching my directory for code using
»::std::sort«, I can just search for »::std::sort« this way.
Otherwise, I would have to search for »sort«, but this would
give many false hits (files where the English word »sort« is
used, or a sort function of some other programing language).
 
B

Barry Schwarz

void addBook(char bookTitle[][51])
{
char choice;
for (int count =0; count < arrSize; count++)
{
if (strcmp(bookTitle[count],"")==0) // if (bookTible[count]=="") won't work, got to use the comparing string function strcmp
{
cout<<"Enter the title of the book: ";
cin.getline(bookTitle[count],51);
cout<<"Do you want to enter another book? (Y/N):";
cin>>choice;
cin.ignore();
if (choice =='Y' || choice =='y');
else
break;
}
else if(bookTitle[arrSize-1]!="")
{
cout<<"No more book may be added to inventory.\n";
}
}
for (int count2=0; count2<arrSize; count2++)
cout<<"Book "<<count2+1<<": "<<bookTitle[count2]<<endl;

}

In the first if statement of this function, you correctly not that
bookTitle=="" will not do what you want. Why then would you use
the exact same construct in the last if statement and expect it to
work any better?
 
N

nick

void addBook(char bookTitle[][51])

char choice;
for (int count =0; count < arrSize; count++)

if (strcmp(bookTitle[count],"")==0) // if (bookTible[count]=="") won't work, got to use the comparing string function strcmp

cout<<"Enter the title of the book: ";
cin.getline(bookTitle[count],51);

cout<<"Do you want to enter another book? (Y/N):";
cin>>choice;
cin.ignore();

if (choice =='Y' || choice =='y');

else if(bookTitle[arrSize-1]!="")

cout<<"No more book may be added to inventory.\n";

for (int count2=0; count2<arrSize; count2++)
cout<<"Book "<<count2+1<<": "<<bookTitle[count2]<<endl;
}



In the first if statement of this function, you correctly not that

bookTitle=="" will not do what you want. Why then would you use

the exact same construct in the last if statement and expect it to

work any better?


You are right, I should continue to use strcmp in the second if statement. Testing some of the suggestions and see if they work. Ian is right too, a lot of clutter, and wait out of my knowledge scope for now, but thanks anyway.
 
I

Ian Collins

Stefan said:
Without »::std«, the text »::std::sort« would be »::sort«,
which wouldn't work. ADL would allow »sort« alone here, but
when I am full-text searching my directory for code using
»::std::sort«, I can just search for »::std::sort« this way.
Otherwise, I would have to search for »sort«, but this would
give many false hits (files where the English word »sort« is
used, or a sort function of some other programing language).

I was referring to the prepended "::". Yes there may be corner cases
where they may be required, but this isn't one of them and adding them
isn't something that should be recommended to a beginner.
 
I

Ike Naar

void addBook(char bookTitle[][51])
{
char choice;
for (int count =0; count < arrSize; count++)
{
if (strcmp(bookTitle[count],"")==0) // if (bookTible[count]=="") won't work, got to use the comparing string function strcmp

Here strcmp() is used two compare two strings ...
{
cout<<"Enter the title of the book: ";
cin.getline(bookTitle[count],51);
cout<<"Do you want to enter another book? (Y/N):";
cin>>choice;
cin.ignore();
if (choice =='Y' || choice =='y');
else
break;
}
else if(bookTitle[arrSize-1]!="")

.... but not here?
{
cout<<"No more book may be added to inventory.\n";
}
}
for (int count2=0; count2<arrSize; count2++)
cout<<"Book "<<count2+1<<": "<<bookTitle[count2]<<endl;

}

Wouldn't it be much more convenient to use std::string,
instead of char[51], to store a book title?
 
I

Ike Naar

void lookUpBook(char bookTitle[][51]) //stub function
{
//char searchBook[51];
char searchBook[51];
cout<<"Enter book title to be searched:";
cin.getline(searchBook,51);

int startScan, minIndex;
char minValue[51];
for (startScan =0; startScan < arrSize-1; startScan++)
{
strcpy(bookTitle[startScan],minValue);

Here you have the order of the strcpy() arguments wrong,
you want to copy the contents of bookTitle[startScan] into minValue,
so:

strcpy(minValue,bookTitle[startScan]);
minIndex= startScan;
for (int index = startScan+1; index < arrSize; index++)
{
if (strcmp(bookTitle[index],minValue)<0)
{
strcpy(minValue,bookTitle[index]);
minIndex=index;
}
}
strcpy(bookTitle[minIndex],bookTitle[startScan]);
strcpy(bookTitle[startScan],minValue);
}


//display book titile array to see if the array sorted correctly
cout<<"The sorted book title are: "<<endl;
for (int count = 0; count < arrSize; count++)
cout<<"Book "<<count+1<<": "<<bookTitle[count]<<endl;
// starting binary search

int first =0, last=arrSize-1, middle, position=-1;
bool found = false;
while (!found && first <= last)
{
middle= (first+last)/2;
if (strcmp(bookTitle[middle],searchBook)==0)
{
found = true;
position=middle;
}
else if (strcmp(bookTitle[middle],searchBook)>0)
last=middle-1;
else
first=middle+1;
}
if (position==-1)
cout<<"The book does not exist in inventory.\n\n";
else
cout<<"The book is found record "<<position<<". \n\n";

}
void addBook(char bookTitle[][51])
{
char choice;
for (int count =0; count < arrSize; count++)
{
if (strcmp(bookTitle[count],"")==0) // if (bookTible[count]=="") won't work, got to use the comparing string function strcmp
{
cout<<"Enter the title of the book: ";
cin.getline(bookTitle[count],51);
cout<<"Do you want to enter another book? (Y/N):";
cin>>choice;
cin.ignore();
if (choice =='Y' || choice =='y');
else
break;
}
else if(bookTitle[arrSize-1]!="")
{
cout<<"No more book may be added to inventory.\n";
}
}
for (int count2=0; count2<arrSize; count2++)
cout<<"Book "<<count2+1<<": "<<bookTitle[count2]<<endl;

}
 
S

Stefan Ram

Juha Nieminen said:
If you are going to make the comparator take std::string objects,
why not make the original data std::string objects as well?

Because (e-mail address removed) wrote:
|How do I sort with char array type instead of string?
¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯
(Also, what exactly is the point in writing "!(r<l)" instead of "l<r"?)

A class might have < overloaded but not >=. For example,
::std::error_category. So !(r<l) is more generic.
 
S

Stefan Ram

Juha Nieminen said:
We have a perfectly good and efficient std::sort(), and you have to
use that horrendous algorithm that shall not be named. Why?

Then, be so kind as to replace »...« in

void sort( char a[][ 51 ], size_t const z ){ ... }

by an implementation using ::std::sort(), so that
»sort« has the semantics required by the OP.
 
N

nick

void addBook(char bookTitle[][51])

char choice;
for (int count =0; count < arrSize; count++)

if (strcmp(bookTitle[count],"")==0) // if (bookTible[count]=="") won't work, got to use the comparing string function strcmp



Here strcmp() is used two compare two strings ...


cout<<"Enter the title of the book: ";
cin.getline(bookTitle[count],51);

cout<<"Do you want to enter another book? (Y/N):";
cin>>choice;
cin.ignore();

if (choice =='Y' || choice =='y');

else if(bookTitle[arrSize-1]!="")



... but not here?


cout<<"No more book may be added to inventory.\n";


for (int count2=0; count2<arrSize; count2++)
cout<<"Book "<<count2+1<<": "<<bookTitle[count2]<<endl;
}



Wouldn't it be much more convenient to use std::string,

instead of char[51], to store a book title?

the exercise required me to use char var instead of string. Thanks for pointing out the second if statement.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,046
Latest member
Gavizuho

Latest Threads

Top