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;'將提供最簡單的解決方案。您的排序條件將根據排序標準而改變。 –