Как отсортировать членов структуры по одному и тому же индексу массива? - PullRequest
0 голосов
/ 14 июня 2019

Я работаю над программой на C ++, но обнаружил, что функция для сортировки массивных элементов структуры, переданных из текстового файла, не была выполнена, и в результате отобразились несортированные элементы структуры.

Эта программапредназначенный для семестрового проекта моего университетского курса, где я сделал базовую программу совместного использования езды на основе C ++.Программа должна прочитать текстовый файл, содержащий информацию о драйвере, и передать ее в структурированные структуры, где она затем начнет сортировку от самой низкой до самой высокой цены и отобразит отсортированные элементы структуры.Я провел небольшое исследование учебника по C ++ и даже зашел на несколько форумов, чтобы найти похожие проблемы, но я продолжал получать те же результаты, что и текстовый файл, который был изначально.

Вот содержимое текстового файла дляссылка.

Annie Aliston
0174987723
Range Rover Evoque
60
6.00

Riley Winston
0174965739
Ford Everest
70
2.50

Вот мое кодирование

#include <iostream>
#include <iomanip>
#include <fstream>
#include <string.h>

using namespace std;

struct ProSort
{
    char nameProvider[10][40]; //40 character limit for nameProvider
    char numPhoneProvider[10][11]; //11 character limit for numPhoneProvider
    char nameVehicle[10][40]; //40 character limit for nameVehicle
    double KMh[10];
    double price[10];
};

ProSort sortingS[7]; //7 set of structs, but I'll put one of the said struct in the sorting function as an example below.

void sortS(ProSort, int);

void share_ride_sort_input(ProSort sortingS[], fstream& File)
{
    File.open("sList/s4-Wheels.txt", ios::in);
    {
        if (File.is_open())
        {
            int a = 0;
            while (!File.eof())
            {
                File >> ws;
                File.getline(sortingS[0].nameProvider[a], 40);
                File >> ws;
                File.getline(sortingS[0].numPhoneProvider[a], 11);
                File >> ws;
                File.getline(sortingS[0].nameVehicle[a], 40);
                File >> sortingS[0].KMh[a];
                File >> sortingS[0].price[a];

                //Contents of the text file will be assigned to the struct members above

                a++; //Array index number will increase until the end of the text file
            }
        }
    }
    File.close();
}

void sortS(ProSort sortingS, int SIZE) //The sorting function for said issue above
{
    int index;
    int smallestIndex;
    int location;
    char temp[100];
    double temp2;

    for (index = 0; index < SIZE - 1; index++)
    {
        smallestIndex = index;

        for (location = index + 1; location < SIZE; location++)
        {
            if (sortingS.price[index] > sortingS.price[smallestIndex]) 
            {
                smallestIndex = location;

                strcpy(temp, sortingS.nameProvider[smallestIndex]);
                strcpy(sortingS.nameProvider[smallestIndex], sortingS.nameProvider[index]);
                strcpy(sortingS.nameProvider[index], temp);

                strcpy(temp, sortingS.numPhoneProvider[smallestIndex]);
                strcpy(sortingS.numPhoneProvider[smallestIndex], sortingS.numPhoneProvider[index]);
                strcpy(sortingS.numPhoneProvider[index], temp);

                strcpy(temp, sortingS.nameVehicle[smallestIndex]);
                strcpy(sortingS.nameVehicle[smallestIndex], sortingS.nameVehicle[index]);
                strcpy(sortingS.nameVehicle[index], temp);

                temp2=sortingS.KMh[smallestIndex];
                sortingS.KMh[smallestIndex]=sortingS.KMh[index];
                sortingS.KMh[index]=temp2;

                temp2=sortingS.price[smallestIndex];
                sortingS.price[smallestIndex]=sortingS.price[index];
                sortingS.price[index]=temp2;

            // Basically all of the arrayed struct members with the same array index will move together as one whole set of driver info until every set of struct members is sorted
            }
        }
    }
}

void share_ride_output(ProSort sortingS[], fstream& File) //Function for displaying the sorted struct members by writing to a text file.
{
    File.open("sList/s4-Wheels-sorted.txt", ios::out);
    {
        if (File.is_open())
        {
            for(int i=0; i<2; i++)
            {
                File<<sortingS[0].nameProvider[i]<<endl;
                File<<sortingS[0].numPhoneProvider[i]<<endl;
                File<<sortingS[0].nameVehicle[i]<<endl;
                File<<sortingS[0].KMh[i]<<" km/h"<<endl;
                File<<"£"<<sortingS[0].charge[i]<<endl;
                File<<"\n";
            } //This is for writing 2 sets of struct members that was assigned in the share_ride_sort_input function to another text file.
        }
    }
    File.close();
}

int main()
{
    fstream File;
    const int SIZE = 7;

    share_ride_sort_input(sortingS, File);

    for(int i=0; i<7; i++) //Originally this was meant for 7 car classes, but only the struct members from the s4-wheels.txt file will be put as an example
    {
        sortS(sortingS[i], SIZE);
    }

    share_ride_output(sortingS, File); //Sorted struct members will be written to a text file.

    return 0;
}

Я ожидаю, что вывод в текстовый файл будет:

Riley Winston
0174965739
Ford Everest
70
2.50

Annie Aliston
0174987723
Range Rover Evoque
60
6.00

Но вместо этого я получилвыходные данные должны быть отсортированы следующим образом:

Annie Aliston
0174987723
Range Rover Evoque
60
6.00

Riley Winston
0174965739
Ford Everest
70
2.50

Сообщение об ошибке не отображается, так как программа работает без каких-либо предупреждений от компилятора.Я бы предположил, что я сделал что-то не так в формуле сортировки, но я не мог заставить другие решения работать.

1 Ответ

0 голосов
/ 14 июня 2019

Основная проблема с вашим кодом в том, что на самом деле это не C ++.В основном это C, с которым гораздо сложнее справиться.

Вторая проблема, когда кто-то указал в комментарии, вы поменяли подсказку на задачу.Вместо этого, создавая массив структур, вы создали массивы внутри структуры, что в данном случае еще более усложнило ситуацию.

Когда вы пишете код на C ++, не используйте такие функции C, как: char[] для строк (используйте std::string), массивы C SomeType variable[number] (используйте std::vector или std::array).

Начните с чего-то подобного и используйте std::sort, и это будет довольно просто:

struct Ride {
    std::string dirver;
    std::string phone;
    std::string vehicle;
    double distance;
    double price;
};


std::istream& loadRide(std::istream& input, Ride& ride)
{
    input >> std::ws; // consume white spaces in front
    std::getline(input, ride.dirver);
    std::getline(input, ride.phone);
    std::getline(input, ride.vehicle);
    return input >> ride.distance >> price; 
}

std::istream& loadRides(std::istream& input, std::vector<Ride>& rides)
{
    rides.clear();
    Ride ride;
    while(loadRide(input, ride)) {
        rides.push_back(ride);
    }
}

std::vector<Ride> loadRidesFromFile(const std::string& fileName)
{
    std::ifstream f{ fileName };
    std::vector<Ride> rides;
    loadRides(f, rides);
    return rides;
}
...