парсинг файла с использованием getline () в новый файл, игнорируя при этом повторяющиеся записи - PullRequest
0 голосов
/ 31 марта 2020

Я пытаюсь написать программу, которая запрашивает у пользователя файл и путь к нему, а затем читает файл. Затем он анализирует текст в файле и сохраняет его в векторе после анализа данных и разделения его на несколько категорий (отдел, код изделия, количество и стоимость).

У меня возникли некоторые проблемы зная, как правильно использовать getline (), и я не уверен в некоторых его аспектах. В целом, я пытаюсь понять, как назначить каждому элементу соответствующую переменную объекта, в настоящее время мне не хватает опыта, чтобы делать такие вещи, а также использовать OOP.

Текст, содержащийся в файл будет выглядеть следующим образом.

21 Music 64679-701 487 28.77
22 Outdoors 63739-141 195 83.23
23 Books 0268-1154 976 65.17

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

main. cpp

    #include <stdio.h>
    #include <stdlib.h>
    #include <iostream>
    #include <string>
    #include <libgen.h>
    #include <fstream>
    #include <sstream>
    #include <vector>
    #include <algorithm>
    #include "Record.h"
    using namespace std;

    int main() {

        vector<Record> records; //vector of type Records to hold each "Line" of input file
        string filename;        // File name and path stored as string

        /**
         * Prompts user for the name of input file and stores in string variable filename
         *
         */
        cout << "please enter the name of your file with file path:" << endl;
        cin >> filename;
        ifstream ifs { filename.c_str() };
        if (!ifs) {
            cerr << " Can't open file " << filename << endl;
            return 1;
        }

        string path = filename.substr(0, filename.find_last_of("\\/"));
        string file = filename.substr(filename.find_last_of("\\/") + 1,
                filename.length());
        if (path.compare(file) == 0) {
            path == "";
        }
        //test for file and file path

        cout << "Path portion of " << filename << " is " << path << endl; //
        cout << "File portion of " << filename << " is " << file << endl; // path + "new_" + file + ".cvs", make new file with new path

        /**
         * Put each line of input file in to the records vector
         */

        string line; //strings for each parameter of the vector object


        while (getline(ifs, line)) {

            Record newRecord(line);

//Here is where I'm having trouble with using get line to parse and store the information. 
//It is incorrect at the moment, and I have the start of how I think I should be going about it.


// check if this record exists in the vector, if not add, else ignore

            records.push_back(newRecord);

        }
        ifs.close(); //closes the stream

        return 0;
    }

Запись.ч

#ifndef RECORD_H_
#define RECORD_H_

#include <iostream>
#include <string>

class Record {
public:

    //Constructor
    Record(std::string s); //pass this string to our Record class

    //De-constructor
    virtual ~Record();

    //overloaded "==" and "<" comparison operators

    friend bool operator ==(const Record &a, const Record &b);

    //friend bool operator <(const Record &a, const Record &b);  //Do not need at this time.

    //Overloaded "<<" operator

    friend std::ostream& operator <<(std::ostream&, const Record&);


private:
        std::string department;
        std::string item_code;
        int quantity;
        double cost;

};

#endif /* RECORD_H_ */

Запись. cpp

#include <string>
#include "Record.h"

using namespace std;

Record::Record(string s) {

    /**
     * Create a string stream from 's' and use getline(stringStream, line, ",") to
     * read each element from the string using the "," as the delimiter. Assign
     * each element to the appropriate object variable
     */
     //getline(s, line.cost, line.department, line.item_code, line.quantity, ",");
}

Record::~Record() {
    // TODO Auto-generated destructor stub
}

//overloaded "==" and "<" comparison operators

bool operator ==(const Record &lhs, const Record &rhs){
    return (lhs.cost == rhs.cost && lhs.department == rhs.department &&
            lhs.item_code == rhs.item_code && lhs.quantity == rhs.quantity);
}

/**bool operator <(const Record &a, const Record &b){ //do not need at this time

}
**/

//Overloaded "<<" operator
std::ostream& operator <<(std::ostream& os, const Record& r){
    os << r.department << ',' << r.item_code << ',' <<  r.quantity << ',' << r.cost;
    return os;

}
...