我正在尝试通过我拿起的一本书自学 C++。其中一个练习是获取用户输入的颜色数组作为字符串对象。然后他们说要使用关系运算符对用户输入的颜色实现选择排序。我已经开始了我认为是正确的轨道,但我遇到了障碍,我不确定它有什么问题。它编译,它只是不会返回排序的值(我认为)任何对我已经拥有的帮助将不胜感激
void selectionSort(char [], int);
int main()
{
const int SIZE = 80;
char colour[SIZE];
cout << "Enter the 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;
}
最佳答案
你的 selectionSort 看起来没问题,但是调用的时候有问题。
selectionSort(colour, SIZE);
这里你告诉你的算法根据颜色对 SIZE 字符进行排序,因为 SIZE 是 80,它将对前 80 个字符进行排序,但是你要求用户只输入五个字符(这里我假设用户应该输入 5颜色的第一个字母,如果您希望用户输入颜色名称,您应该阅读 5 个字符串,而不是 5 个字符)。
如果用户输入有 5 个字符,colour[5] 将有 nil 终止符,即 0,排序后将位于 colour[0],这将导致空字符串。
尝试只对您想要的字母进行排序:
selectionSort(colour, strlen(colour));
关于数组的 C++ 选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7480114/