我正试图通过我读过的一本书自学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;
}
答案 0 :(得分:0)
您的selectionSort似乎很好,但是当您调用它时会出现问题。
selectionSort(colour, SIZE);
在这里你告诉你的算法从颜色中对SIZE字符进行排序,因为SIZE是80,它会对80个第一个字符进行排序,但是你要求用户只输入5个字符(这里我假设用户应该输入5个字符)第一个颜色字母,如果您希望用户输入颜色名称,您应该读取5个字符串,而不是5个字符。)
如果用户输入有5个字符,color [5]将具有nil-terminator,即0,并且在排序后将为color [0],这将导致空字符串。
尝试仅排序您想要的字母:
selectionSort(colour, strlen(colour));
答案 1 :(得分:0)
我必须订阅一项动议,禁止所有使用iostream
和char[]
教授C ++的书籍。
他们语无伦次。
如果std :: string保留了一个“复杂类型”,地狱cout
是什么?
如果cout
保留了“以”开头的基本对象“,那么std::string
应该。