Sort an input file for a specific value

Hello,

I am trying to sort an input file by a specific value (price), then print the sorted list to an output file.

Example input text (how it it formatted in my code to print to the screen. I would like to sort by price and save to an output file.
*Must use constructors* ?? All of my code right now is running using structs to store data variables from each text file.



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
void bookFunction()
{
    ///Open files

    ifstream inputB;
    inputB.open("Book.txt");

    int bookInventory;

    inputB >> bookInventory; ///read first line to set array lengyh

    book booksArray[bookInventory]; ///declare array

    ///Verify file is open

    if(!inputB)
    {
        cout << "File not found" <<endl;
    }
    else
    {
        ///Build array
        for(int i=0; i < bookInventory; i++)
        {
            book myBook;

            inputB >> myBook.title >> myBook.hardcover >>
                  myBook.noOfPages >> myBook.price >> myBook.totalInventory >> myBook.datePublished;

            booksArray[i] = myBook;

        }

        ///Print Results

        cout << string(83, '-') << endl; /// 83 dashes??
        cout << setw(43) << "Books" << endl;
        cout << string(83, '=') << endl; /// second verse same as the first

        cout << setw(20) << left << " Title"  << "|"
            << setw(11) << " Hardcover"  << "|"
            << setw(14) << " No. of Pages"  << "|"
            << setw(11) << " Inventory"  << "|"
            << setw(7)  << " Price" << "|"
            << setw(15) << " Date Published" << endl;

        cout << string(83, '-') << endl; /// last verse same as the first

        for (int i=0; i < bookInventory; i++)
        {
            book myBook;
            myBook = booksArray[i];

            cout << setw(20) << left << myBook.title  << "|"
                << setw(11) << right << boolalpha << myBook.hardcover  << "|"
                << setw(14) << right << myBook.noOfPages  << "|"
                << setw(11) << right << myBook.totalInventory  << "|"
                << setw(7)  << right << fixed << setprecision(2) << myBook.price << "|"
                << setw(15) << right << myBook.datePublished<< endl;
        }
    }

    ///close files

    inputB.close();

    cout << endl << endl;

}


  Book Document:
-----------------------------------------------------------------------------------
                                      Books
===================================================================================
 Title              | Hardcover | No. of Pages | Inventory | Price | Date Published
-----------------------------------------------------------------------------------
PrideandPrejudice   |       true|           209|         10|  10.99|     04:01:2010
ToKillaMockingbird  |      false|           276|          3|  10.99|     03:10:2013
TheGreatGatsby      |       true|           257|          3|   7.99|     06:21:2000
JaneEyre            |       true|           294|          8|  10.99|     06:01:2005
TheCatcherintheRye  |       true|           171|          2|  10.99|     07:06:2006
LittleWomen         |      false|           354|          3|  10.99|     02:26:2008
HuckleberryFin      |       true|           269|          2|   7.99|     02:27:2015
MobyDick            |      false|           278|          1|  10.99|     07:13:2012
AliceinWonderland   |       true|           494|          7|  10.99|     08:17:2015
LordoftheFlies      |       true|           133|          1|  10.99|     06:06:2016
AnimalFarm          |       true|           119|          5|   7.99|     03:22:2015
GreatExpectations   |      false|           287|          9|  10.99|     06:13:2013
1984                |      false|           275|          8|  10.99|     04:14:2017
GreatExpectations   |       true|           360|          7|  10.99|     07:23:2016
Frakenstein         |      false|           146|          3|  10.99|     03:20:2010
TheScarletLetter    |       true|           248|          5|  10.99|     02:28:2014


I would like to use one simple function to print all of the sections to one file:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
void sequencedOrdersFile ()
{
    ofstream outData;

    outData.open("SequencedOrders.txt");

    ///Sort orders by price (high to low)
    for ()
    {
        ...
    }

    ///Print to outfile
    outData << ///sorted information for all items

    ///Close outfile
    outData.close();
}



...And i need to change true to yes and false to no...
Last edited on
Please show the declaration of book.
1
2
3
4
5
6
7
8
9
struct book
{
    string title;
    bool hardcover{};
    int noOfPages{};
    double price{};
    int totalInventory{};
    string datePublished;
};
I think that I need to split the function into two... "read" and "print"
I have been struggling with that.

Than in the sort function, I would only need to call the "read" functions and sort to the output
Suggestion. Store the books in a std::vector. Then you can use the standard sort function.
http://www.cplusplus.com/reference/algorithm/sort/?kw=sort
You will want to specify your own compare function that compares on price.

1
2
3
4
5
6
7
8
9
10
bool myCompare (book & a, book & b)
{  return a.price < b.price;
}

  std::vector<book> bookinv;

  //  For each book
  bookinv.push_back (myBook);

  sort (bookinv.begin(), bookinv.end(); myCompare);
I think that I can get away with sorting the books by price in the array, without building a specific sort function.
You can use std::sort on the array (not tried):

 
std::sort(booksArray, booksArray + bookInventory, [](const auto& b1, const auto& b2) {return b1.price < b2.price;});


change true to yes and false to no


As .hardcover is type bool, then something like (not tried):

1
2
3
constexpr const char* const yesno[] {"no", "yes"};
....
std::cout << yesno[myBook.hardcover];


It would be helpful if you posted the whole code.

Last edited on
> AbstractionAnon: Store the books in std::vector
+1

This is not standard C++ (though it is a non-standard dialect known as gnu++)

1
2
3
4
5
ifstream inputB;
inputB.open("Book.txt");
int bookInventory;
inputB >> bookInventory; ///read first line to set array lengyh
book booksArray[bookInventory]; // *** error:  bookInventory is not a constant 


Use a vector by default when the size is not a constant known at compile-time.
We can sort that as easily as we could sort an array.
:) I don't understand why c-style arrays are taught before std::vectors, or c-style strings before std::string, or raw pointers...... Vectors are as easy to use (easier in some cases) than c-style arrays!

As I've said before - C++ isn't c!
Thank you everyone. I was able to finish the project.
Topic archived. No new replies allowed.