Soooo I spoke too soon. For some reason I'm getting some weird output when I run my program. Mainly theres seems to be random duplicates appearing and I'm not too sure why.
My current code:
Code:
#ifndef COLLECTION_H
#define COLLECTION_H
#include <iostream>
#include <fstream>
#include <vector>
#include <sstream>
#include <algorithm>
#include <string>
#include <iomanip>
using namespace std;
class Collection
{
private:
struct Book
{
string title;
string author;
string genre;
};
vector<Book> books;
public:
Collection()
{
Book book;
ifstream inFile;
string filename, text;
inFile.open("Books.txt");
if (inFile.fail())
{
cout << "File not found. Please enter file name: ";
cin >> filename;
inFile.open(filename);
}
while (getline(inFile,text))
{
stringstream lineStream(text);
getline(lineStream, book.title, ',');
getline(lineStream, book.author, ',');
getline(lineStream, book.genre);
books.push_back(book);
}
inFile.close();
}
void sortByTitle()
{
sort(books.begin(), books.end(), [](Book b1, Book b2) { return b1.title < b2.title; });
}
void sortByAuthor()
{
sort(books.begin(), books.end(), [](Book b1, Book b2) { return b1.author < b2.author; });
}
void sortByGenre()
{
sort(books.begin(), books.end(), [](Book b1, Book b2) { return b1.genre < b2.genre; });
}
void output()
{
cout << left << setw(41) << "Title" << left << setw(25) << "Author" << setw(20) << "Genre\n";
for (auto val:books)
{
cout << left << setw(40) << val.title << left << setw(25) << val.author << setw(20) << val.genre << endl;
}
}
};
#endif
This is the output I get when I put in sort by title. It sorts the titles correctly however there are a bunch of duplicate outputs prior to the correct sorted file. It is different when sorting by author & genre but the error in code must be the same for all sorting options.
Code:
There are 3 fields for each book: title, author and genre.
Please select an option to sort the books by a particular field by entering the correct number.
1 = Sort by title
2 = Sort by author
3 = Sort by genre
Please enter a sorting option: 1
Title Author Genre
Tony Gaddis technical
Liu Cixin science fiction
Kenzo Kitakana fiction
Gabriel Garcia Marquez fiction
Carol Dweck psychology
Ken Follet historical fiction
Ken Follett historical fiction
Bjarne Stroustrup technical
Elmarsi & Navathe technical
Ashes Kenzo Kitakana fiction
Fall of Giants Ken Follet historical fiction
Fundamentals of Database Systems Elmarsi & Navathe technical
Mindset: The New Psychology of Success Carol Dweck psychology
One Hundred Years of Solitude Gabriel Garcia Marquez fiction
Replay Ken Grimwood fantasy
Starting out with c++ Tony Gaddis technical
The C++ Programming Language Bjarne Stroustrup technical
The Dark Forest Liu Cixin science fiction
The Pillars of the Earth Ken Follett historical fiction
Not exactly sure why this is happenig. There are no white spaces in my input file but it seems to be picking up random lines due to something?