2
我正在研究一个模仿“动物采用代理”的程序。我从文件中读取,其中包含动物名称,品种,年龄,价格和性别列表。我有两个文件,一个是猫和狗。从阅读文件中对不同类型的多个数组进行排序
用户可以通过上面列出的类别对列表进行排序。我目前有一个for循环,可以精确地对他们选择的类别进行排序;但是,其他类别不会相应地订购。我不知道如何去做这件事。 下面是我的代码的简明版本,它只允许访问狗部分并按名称排序,而不是选择如何排序。
#include <iostream>
#include <fstream>
#include <istream>
#include <cctype>
#include <string>
#include <string.h>
#include <cstring>
#include <iomanip>
#include <vector>
#include <algorithm>
using namespace std;
int animalMenu, animalCount, animAge[50], animPrice[50], entry = 0, total;
string animType, animName[50], animBreed[50], animSex[50], takeHomeWith;
ifstream animalInform;
const int WIDTH = 8, BIG_WIDTH = 12;
void sortingHat(string[]);
void innerSorting(string[], int);
int main() {
animalInform.open("Dog Information.txt");
animType = "dogs";
// SET NUMBER OF ANIMALS IN FILE
animalInform >> animalCount;
cout << "There are " << animalCount << " " << animType << "! \n";
// SETS ALL THE VALUES BY READING FROM FILE
for (int entry = 0; entry < animalCount; entry++) {
animalInform >> animName[entry] >> animBreed[entry] >> animAge[entry] >> animPrice[entry] >> animSex[entry];
cout << setw(BIG_WIDTH) << animName[entry] << setw(BIG_WIDTH) << animBreed[entry] << setw(WIDTH) << animAge[entry] << setw(WIDTH) << animPrice[entry] << setw(WIDTH) << animSex[entry] << endl;
}
// CLOSE FILE
animalInform.close();
// CALL FUNCTION TO SORT (BY NAME ONLY)
sortingHat(animName);
cout << endl;
// DISPLAY NEWLY SORTED LIST
for (int entry = 0; entry < animalCount; entry++) {
cout << setw(BIG_WIDTH) << animName[entry] << setw(BIG_WIDTH) << animBreed[entry] << setw(WIDTH) << animAge[entry] << setw(WIDTH) << animPrice[entry] << setw(WIDTH) << animSex[entry] << endl;
}
system("pause");
}
void sortingHat(string sortingString[])
{ // SORTS DATA AND PUTS IT IN ORDER, ALPHABETICAL --
for (int outer = 0; outer <= animalCount; outer++)
{
for (int entry = 0; entry <= (animalCount - 2); entry++) {
string temporary[50];
if (sortingString[entry] > sortingString[entry + 1])
innerSorting(sortingString, entry);
}
}
}
void innerSorting(string sorter[], int entry)
{
string temporary[50];
temporary[entry] = sorter[entry];
sorter[entry] = sorter[entry + 1];
sorter[entry + 1] = temporary[entry];
}
所以我显然没有任何东西可以让其他条目跟随。 所以,如果我选择的名称进行排序,我的输出(这是写在我的文件)会从
Brienne Shepard 6 $150 F
Jon Labrador 3 $200 M
Aemon ShihTzu 10 $50 M
到
Aemon Shepard 6 $150 F
Brienne Labrador 3 $200 M
Jon ShihTzu 10 $50 M
而且我希望它这样做(如果选择按名称排序):
Aemon ShihTzu 10 $50 M
Brienne Shepard 6 $150 F
Jon Labrador 3 $200 M
你在课堂上使用过载体吗? –
@CaptainGiraffe不,她确实告诉我们,如果我们想要的话,我们可以使用矢量。你会推荐使用那些而不是数组吗? –
总是。一个'vector adoptable_animals;'将提供最简单的解决方案。您的排序条件将根据排序标准而改变。 –