C++ Selection for Array
I'm trying to teach myself C++ through a book I picked up. One of the exercises is to get an user-inputted array of colours as string objects. Then they say to implement a selection sort on the user-inputted colours using relational operators. I have already started on what I think is the right track, but I have hit a road block and I am not sure what is wrong with it. It compiles, it just won't return the sorted vales (I think) Any assistance with what I have already would be greatly appreciated
void selectionSort(char [], int);
int main()
{
const int SIZE = 80;
char colour[SIZE];
cout << "Enter t开发者_StackOverflow社区he names of five kinds of fruit:" << endl;
cin.getline(colour, SIZE);
cout << colour << endl;
selectionSort(colour, SIZE);
cout << colour << endl;
return 0;
}
// SORT
void selectionSort(char shade[], int size)
{
int startScan, minIndex, minValue;
for (startScan = 0; startScan < (size - 1); startScan++)
{
minIndex = startScan;
minValue = shade[startScan];
for (int index = startScan + 1; index < size; index++)
{
if (shade[index] < minValue)
{
minValue = shade[index];
minIndex = index;
}
}
shade[minIndex] = shade[startScan];
shade[startScan] = minValue;
}
cout << shade[size] << endl;
}
Your selectionSort seems fine, but there is a problem when you call it.
selectionSort(colour, SIZE);
Here you tell your algorithm to sort the SIZE chars from colour, since SIZE is 80, it will sort the 80 first characters, but you ask the user to type only five characters (here I am assuming that the user should input 5 first letters of colors, if you expect the user to type the color name you should read 5 strings, not 5 chars).
If the user input have 5 characters, colour[5] will have the nil-terminator, which is 0, and will be at colour[0] after the sort, which will result in an empty string.
Try sorting only the letters you want:
selectionSort(colour, strlen(colour));
I have to subscribe a motion to ban all the books that teach C++ with iostream
and char[]
.
They are incoherent.
If std::string is retained a "complex type" what the hell cout
is?
If cout
is retained a "basic object to start with", so std::string
should.
精彩评论