I am doing this program which reads a CSV file and enters it in a tree, until now I have managed to create the tree and it shows them in order, however with the search I have a failure since it does not show the information of the element that is being searched , someone who can help me correct the fault, thanks....
The csv file contains the data(contains several but I leave these for example.):
1,name1,number1
2,name2,number2
3,name3,number3
#include <iostream>
#include <iomanip>
#include <fstream>
#include <memory>
#include <string>
#include <sstream>
#include <vector>
#include <utility>
#include <experimental/optional>
intmax_t dato;
struct Person {
intmax_t key;
std::string name;
intmax_t num;
};
struct Node : Person {
Node(const Person &person) : Person(person) {}
std::unique_ptr<Node> left, right;
void insert(const Person &person);
};
void Node::insert(const Person &person) {
/* recur down the tree */
if (key > person.key) {
if (left)
left->insert(person);
else
left = std::make_unique<Node>(person);
} else if (key < person.key) {
if (right)
right->insert(person);
else
right = std::make_unique<Node>(person);
}
}
std::vector<Person> persons;
void inorder(Node *root) {
if (root) {
// cout<<"\t";
inorder(root->left.get());
std::cout << "\tID: "<< root->key << "\tName: "<< root->name << "\t\tNum: " << root->num << '\n'; //'\t' ' '
inorder(root->right.get());
}
}
std::experimental::optional<Person> busqueda(Node *root, intmax_t dato) {
if(root==NULL){
return {};
}
else if(root->key==dato){
return *root;
}
else if(dato<root->key){
return busqueda(root->left.get(),dato);
}
else{
return busqueda(root->right.get(),dato);
}
}
int main() {
std::unique_ptr<Node> root;
std::ifstream fin("data.txt");
if (!fin) {
std::cout << "File not open\n";
return 1;
}
std::string line;
const char delim = ',';
std::cout<<"\t\tData\n"<<std::endl;
while (std::getline(fin, line)) {
std::istringstream ss(line);
Person person;
ss >> person.key;
ss.ignore(10, delim);
std::getline(ss, person.name, delim);
ss >> person.num;
if (ss) persons.push_back(person);
}
for (unsigned int i = 0; i < persons.size(); i++) {
std::cout << std::setw(10)<<"ID: " << persons[i].key << std::setw(30)<<"Name: "
<< persons[i].name << std::setw(20) <<"Num: "<< persons[i].num << '\n';
if (!root) root = std::make_unique<Node>(persons[i]);
else root->insert(persons[i]);
}
std::cout << "\n\n\t\tInorder:\n\n";
inorder(root.get());
std::cout<<" Enter data: "; std::cin>> dato;
busqueda(root.get(),dato);
if(busqueda(root.get(),dato)){
std::cout<<"Data found"<<std::endl;
std::cout<<root->name;//does not show the wanted, only the first of the document.
}
else{
std::cout<<"\nData not found"<<std::endl;
}
return 0;
}
From the comments you throw away the result of your search in the following statement:
busqueda(root.get(),dato); returns an optional value std::experimental::optional but you don't make use of the value.
You test the value with if(busqueda(root.get(),dato)){ but since you did not store the result you both searched a second time and do not have a way to get the Person object.
Instead you can do this to get the person object and show its name:
std::cout << " Enter data: "; std::cin >> dato;
auto result = busqueda(root.get(), dato);
if (result) {
std::cout << "Data found" << std::endl;
std::cout <<result->name; // This should be the name of the found Person
}
else {
std::cout << "\nData not found" << std::endl;
}
Related
I write a small Store that contain Item. I create two function one to print content of file one to sort the records and insert them back into file. With the initializer list it display correctly the content of file, but said that there is "Error with file". How to correct this issue and what is the best way to create a binary file in constructor
#pragma once
#include <iostream>
#include <fstream>
#include <cstring>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
struct Item
{
char name[20];
int code;
float price;
int quantity;
Item() { code = 0, price = 0, quantity = 0;
char name1[20] = { 0 }; strcpy_s(name, 20, name1);
}
Item(const char* name, int code, float price, int quantity)
{
strcpy_s(this->name, strlen(name) + 1, name);
this->code = code;
this->price = price;
this->quantity = quantity;
}
friend ostream& operator<<(ostream& os, Item& item)
{
os << "Name: " << item.name << endl;
os << "code: " << item.code << endl;
os << "price: " << item.price << endl;
os << "quantity: " << item.quantity << endl << endl;
return os;
}
bool operator!()
{
return code != 0;
}
};
class Store
{
private:
int size = 100;
fstream file;
string fileName;
public:
Store(string fname);
~Store();
Store& operator+=(Item& myItem);
friend ostream& operator<<(ostream&, Store&);
void sortStore();
};
#include "Store.h"
Store::Store(string fname) : file(fname,ios::binary)
{
Item tmp;
if (!file)
cout << "Error with file" << endl;
for (int i = 0; i < size; i++)
file.write((char*)&tmp, sizeof(Item));
//file.close();
file.open(fname, ios::binary | ios::in | ios::out);
}
Store::~Store()
{
file.close();
}
Store& Store::operator+=(Item& myItem)
{
file.write((char*)&myItem, sizeof(myItem));
return (*this);
}
ostream& operator<<(ostream& out, Store& store)
{
Item tmp;
store.file.seekg(0, ios::beg);
for (int i = 0; i < store.size; i++)
{
store.file.read((char*)&tmp, sizeof(Item));
if (!tmp)
cout << i << ": " << tmp;
}
return out;
}
void Store::sortStore()
{
Item tmp;
vector<Item> items;
file.seekg(0, ios::beg);
while (!file.eof())
{
file.read((char*)&tmp, sizeof(Item));
items.push_back(tmp);
}
sort(items.begin(), items.end(), [](Item& first, Item& second)
{
return first.code < second.code;
});
file.clear();
remove("store.dat");
Store("store.dat");
file.seekp(0, ios::beg);
for (auto it = items.begin(); it < items.end(); it++)
file.write((char*)&(*it), sizeof(Item));
}
int main()
{
Store ourStore("store.dat");
Item apple("apple", 45, 12.2, 10);
Item ananas("ananas", 12, 27, 10);
Item strawberry("strawberry", 1, 24.2, 5);
Item banana("banana",23,14.2, 12);
ourStore.operator+=(apple);
ourStore.operator+=(ananas);
ourStore.operator+=(strawberry);
ourStore.operator+=(banana);
int choice = -1;
while (choice != 0)
{
cout << "1.Sorting, 2 Print" << endl;
switch (choice)
{
case 1:
cout << "Sorting" << endl;
ourStore.sortStore();
case 2:
cout << "Print" << endl;
cout << ourStore << endl;
}
cin >> choice;
}
return 0;
}
The local variable file in Store::Store hides the member variable Store::file.
You want an initializer list:
Store::Store : file(fname, ios::binary)
{
// ...
I am working on an assignment for school. I have to create an AVLTree, read data from a text file and then create Professor object with that data. However, when I try and search for a Professor by name, it can't be found. It keeps defaulting to Michael Scott in the program and can't find who I'm looking for. My readFromFile function works perfectly and gets me all the data from the file, so I have the data. At this point it's a matter of issues with the AVL Tree. I'll link everything below.
Driver.cpp:
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include "AVLTree.h"
using namespace std;
void readFromFile(AVLTree *treeAccess) {
int numOfProfs = 0;
string line;
const char *path="/Users/collinchappell/Desktop/Program4Official/Program4Official/ProfessorData.txt";
fstream myFile (path, ios::in);
if (!myFile) {
cout << "Sorry can't read ProfessorData.txt!" << endl;
}
else {
// Splitting up all the data in the .txt file and the looping through using string stream
// Not the best solution, however nothing else would work for me so this is what I went with.
while (getline(myFile, line)) {
string n;
string nT;
string s;
int b1,b2,b3,b4,b5,b6,b7;
replace(line.begin(), line.end(), '$', ' ');
stringstream ss(line);
for (int k = 0; k < 11; k++) {
ss >> n;
ss >> nT;
n = n + " " + nT;
ss >> s;
ss >> b1;
ss >> b2;
ss >> b3;
ss >> b4;
ss >> b5;
ss >> b6;
ss >> b7;
numOfProfs++;
Professor p(n, s, b1, b2, b3, b4, b5, b6, b7);
cout << p;
treeAccess->insertNode(n, &p);
}
}
}
cout << numOfProfs << " Proffesors have added from the file." << endl << endl;
}
int main() {
AVLTree tree;
readFromFile(&tree);
bool cont = true;
while (cont) {
cout << "Which Computer Science professor do you want details about?" << endl;
tree.displayInOrder();
cout << endl << endl << "Type Professor Name: ";
string typeName;
getline(cin, typeName);
while (tree.searchNode(typeName) == NULL) {
cout << "Couldn't find that professor! Please type another: ";
getline(cin, typeName);
}
cout << tree.searchNode(typeName);
cout << "Would you like to search another? (Y/N): ";
string ans;
cin >> ans;
if (ans == "y" || ans == "Y") {
continue;
}
else if (ans == "n" || ans == "N") {
return 0;
}
}
return 0;
}
AVLTree.h:
#ifndef AVLTree_h
#define AVLTree_h
#include <iostream>
#include "Professor.h"
using namespace std;
class AVLTree {
private:
// TreeNode structure
struct TreeNode {
string name;
Professor *prof;
struct TreeNode* left;
struct TreeNode* right;
};
// Root of tree
TreeNode* root;
// Function declarations
void insert(TreeNode *&nodePtr, TreeNode *&newNode);
void destroySubTree(TreeNode *nodePtr);
void displayInOrder(TreeNode *nodePtr) const;
int height(TreeNode *nodePtr);
int diff(TreeNode *nodePtr);
void balance(TreeNode *&temp);
TreeNode* l_rotation(TreeNode *parent) {
TreeNode *temp;
temp = parent->right;
parent->right = temp->left;
temp->left = parent;
return temp;
}
TreeNode* r_rotation(TreeNode *parent) {
TreeNode *temp;
temp = parent->left;
parent->left = temp->right;
temp->right = parent;
return temp;
}
TreeNode* lr_rotation(TreeNode *parent) {
TreeNode *temp;
temp = parent->left;
parent->left = (l_rotation(temp));
return r_rotation(parent);
}
TreeNode* rl_rotation(TreeNode *parent) {
TreeNode *temp;
temp = parent->right;
parent->right = (r_rotation(temp));
return l_rotation(parent);
}
public:
AVLTree() { // Constructor
root = NULL;
}
~AVLTree() { // Destructor
destroySubTree(root);
}
void insertNode(string n, Professor* professor);
Professor* searchNode(string);
// Call private displayInOrder()
void displayInOrder() const {
displayInOrder(root);
}
};
#endif /* AVLTree_h */
AVLTree.cpp:
#include <iostream>
#include "AVLTree.h"
using namespace std;
// Insert a node into the tree recursively
void AVLTree::insert(TreeNode *&nodePtr, TreeNode *&newNode) {
if (nodePtr == NULL) {
nodePtr = newNode;
}
else if (newNode->name < nodePtr->name) {
insert(nodePtr->left, newNode);
balance(nodePtr);
}
else {
insert(nodePtr->right, newNode);
balance(nodePtr);
}
}
// Destory the sub tree
void AVLTree::destroySubTree(TreeNode *nodePtr) {
if (nodePtr) {
if (nodePtr->left) {
destroySubTree(nodePtr->left);
}
if (nodePtr->right) {
destroySubTree(nodePtr->right);
}
delete nodePtr;
}
}
// Display the tree in order
void AVLTree::displayInOrder(TreeNode *nodePtr) const {
if (nodePtr) {
displayInOrder(nodePtr->left);
cout << nodePtr->name << endl;
displayInOrder(nodePtr->right);
}
}
// Get the tree's height
int AVLTree::height(TreeNode *temp) {
int leftHeight, rightHeight;
if (temp) {
leftHeight = height(temp->left);
rightHeight = height(temp->right);
if (leftHeight > rightHeight) {
return leftHeight + 1;
}
else if (leftHeight < rightHeight) {
return rightHeight + 1;
}
else {
return 0;
}
}
return 0;
}
// Get the difference
int AVLTree::diff(TreeNode *temp) {
int l_height = height(temp->left);
int r_height = height(temp->right);
return l_height - r_height;
}
// Balance the tree
void AVLTree::balance(TreeNode *&temp) {
int bal_factor = diff (temp);
if (bal_factor > 1)
{
if (diff(temp->left) > 0) // 2, 1 RIGHT
{
temp = r_rotation(temp);
cout << "\nRIGHT rotation";
}
else // 2, -1 LEFT-RIGHT
{
temp = lr_rotation(temp);
cout << "\nLEFT-RIGHT rotation";
}
}
else if (bal_factor < -1)
{
if (diff (temp->right) > 0) // -2, 1 RIGHT-LEFT
{
temp = rl_rotation(temp);
cout << "\nRIGHT-LEFT rotation";
}
else // -2, -1 LEFT
{
temp = l_rotation(temp);
cout << "\nLEFT Rotation";
}
}
}
// Insert a node, calls the private insert function
void AVLTree::insertNode(string n, Professor *proffesor) {
TreeNode *newNode = NULL; // Pointer to a new node.
newNode = new TreeNode;
newNode->name = n;
newNode->prof = proffesor;
newNode->left = newNode->right = NULL;
// Insert the node.
insert(root, newNode);
}
Professor* AVLTree::searchNode(string s) {
cout << "Name inputted into search: " << s << endl;
cout << endl << "Actual name: " << root->name << endl;
TreeNode *nodePtr = root;
while (nodePtr != NULL) {
if (nodePtr->name == s) {
return nodePtr->prof;
}
else if (nodePtr->name > s) {
nodePtr = nodePtr->left;
cout << "Left -> " << nodePtr << endl;
}
else {
nodePtr = nodePtr->right;
cout << "Right -> " << nodePtr << endl;
}
}
return NULL;
}
Professor.h:
#ifndef PROFESSOR_H
#define PROFESSOR_H
#include <iostream>
#include <iomanip>
using namespace std;
class Professor
{
private:
string name;
string course;
bool clearGrading;
bool goodFeedback;
bool caring;
bool reachable;
bool toughGrader;
bool lectureHeavy;
bool attendance;
public:
Professor(string n, string course, bool cG, bool gF, bool c, bool r, bool tG, bool lH, bool a) {
this->name = n;
this->course = course;
this->clearGrading = cG;
this->goodFeedback = gF;
this->caring = c;
this->reachable = r;
this->toughGrader = tG;
this->lectureHeavy = lH;
this->attendance = a;
}
friend ostream &operator << (ostream &strm, Professor &p)
{
strm << endl << endl;
strm << setw(30) << "Professor:" << setw(20) << p.name << endl;
strm << setw(30) << "Course:" << setw(20) << p.course << endl;
strm << setw(30) << "Clear Grading Criteria:" << setw(20);
if(p.clearGrading == 0) strm << "no"; else strm << "yes";
strm << endl;
strm << setw(30) << "Provides Good Feedback:" << setw(20);
if(p.goodFeedback == 0) strm << "no"; else strm << "yes";
strm << endl;
strm << setw(30) << "Caring:" << setw(20);
if(p.caring == 0) strm << "no"; else strm << "yes";
strm << endl;
strm << setw(30) << "Reachable Outside of Class:" << setw(20);
if(p.reachable == 0) strm << "no"; else strm << "yes";
strm << endl;
strm << setw(30) << "Tough Grader:" << setw(20);
if(p.toughGrader == 0) strm << "no"; else strm << "yes";
strm << endl;
strm << setw(30) << "Lecture Heavy:" << setw(20);
if(p.lectureHeavy == 0) strm << "no"; else strm << "yes";
strm << endl;
strm << setw(30) << "Attendance Mandatory:" << setw(20);
if(p.attendance == 0) strm << "no"; else strm << "yes";
strm << endl;
return strm;
}
};
#endif
ProfessorData.txt:
Michael Scott$CSC1310$0$0$1$1$0$1$1$Jim Halpert$CSC1310$1$1$1$0$0$0$0$Pam Beesly$CSC1300$1$1$1$0$1$0$1$Dwight Schrute$CSC2400$1$1$0$0$1$1$1$Angela Martin$CSC1300$1$0$0$0$1$1$1$Kelly Kapoor$CSC1300$0$0$0$0$0$0$0$Andy Bernard$CSC2400$1$0$1$1$0$1$1$Kevin Malone$CSC1310$0$1$1$1$0$0$0$Meredith Palmer$CSC1310$0$1$1$1$0$0$0$Phyllis Vance$CSC1300$1$1$1$0$1$0$0$Oscar Nunez$2400$1$1$1$1$1$1$1$
Running the program:
11 Proffesors have added from the file.
Which Computer Science professor do you want details about?
Andy Bernard
Angela Martin
Dwight Schrute
Jim Halpert
Kelly Kapoor
Kevin Malone
Meredith Palmer
Michael Scott
Oscar Nunez
Pam Beesly
Phyllis Vance
Type Professor Name: Andy Bernard
Name inputted into search: Andy Bernard
Actual name: Michael Scott
Left -> 0x100704570
Left -> 0x105a045b0
Left -> 0x105b04120
Left -> 0x105b041a0
Name inputted into search: Andy Bernard
Actual name: Michael Scott
Left -> 0x100704570
Left -> 0x105a045b0
Left -> 0x105b04120
Left -> 0x105b041a0
0x7ffeefbfee18Would you like to search another? (Y/N):
As you can see, I've put in some prints to kind of debug what's happening. I believe my objects are not getting inserted into the tree right, or my search function is off. Also, I'm not 100% on the balance function. Any help would be amazing.
I've spent pretty much all day trying to do this, I understand pointers and what a linked list does, but I don't know how to actually code it and all I've found are Java and C examples which don't help because I'm using C++.
Thanks in advance for taking a look at my code and helping me, I really appreciate it considering how many days I've spent stressed out and confused about this. I'm not going to lie so far most of my deleteNode function is probably trash. But like I've said I'm just lost I don't even know where to start or how to progress because I only understand the concepts.
This is my data file.
John Doe 80
Jane Smith 70
Bill Jones 50
Pat Hughes 90
Sam Sosa 40
This is my Header file
#include<string>
using namespace std;
class student {
public:
student(); // constructor method
void st_fn(string fn);
string st_fn();
void st_ln(string ln);
string st_ln();
void st_score(float s);
float st_score();
string st_pass_or_fail();
// need a pointer to the next object
student *nxt_ptr;
protected: // protected can be inherited
float m_score;
string m_ln;
string m_fn;
string m_pf_msg;
};
student::student() //constructor
{
nxt_ptr = NULL;
m_score = 0;
}
void student::st_fn(string fn)
{
m_fn = fn;
}
string student::st_fn()
{
return m_fn;
}
void student::st_ln(string ln)
{
m_ln = ln;
}
string student::st_ln()
{
return m_ln;
}
void student::st_score(float s)
{
m_score = s;
}
float student::st_score()
{
return m_score;
}
string student::st_pass_or_fail()
{
if (m_score >= 60)
m_pf_msg = "PASSED";
else
m_pf_msg = "FAILED";
return m_pf_msg;
}
This is my .cpp file.
#include<iostream>
#include<string>
#include<fstream>
#include "Header.h"
using namespace std;
int display_menu()
{
int option;
cout << endl << endl;
cout << "1. Display List" << endl;
cout << "2. Add a student" << endl;
cout << "3. Delete first student" << endl;
cout << "4. Search by Last Name" << endl;
cout << "5. Exit" << endl;
cin >> option;
return option;
}
student * search_last_name(student *h)
{
student *f = NULL;
student *t = NULL;
string s_ln;
// prompt for last name to search for
cout << "Enter Last Name of the Student";
cin >> s_ln;
if (h != NULL)
{
t = h;
while (t != NULL)
{
if (t->st_ln() == s_ln)
f = t; // found the last name so save t
t = t->nxt_ptr;
}
}
else
cout << "List is empty" << endl;
return f;
}
void add_student(student *&head) // h is the head of the list
{
student *new_st, *r;
string fn, ln;
float s;
cout << "Enter new students first name, last name and score";
cin >> fn >> ln >> s;
// instantiate a new node, use new_st
new_st = new student;
new_st->st_fn(fn);
new_st->st_ln(ln);
new_st->st_score(s);
if (head == NULL)
head = new_st;
else
{
// find the last node, use r for this
// write code
r = head;
while (r->nxt_ptr != nullptr)
r = r->nxt_ptr;
// add to the back of the list
// write code
r->nxt_ptr = new_st;
} // end of else
} // end of add student
student * delete_front(student * head)
{
student *t;
// delete front node
// check for empty list
if (head != NULL)
{
// delete first node
t = head;
head = head->nxt_ptr;
delete(t);
}
else
cout << "List is empty - nothing to delete" << endl;
return head;
}
void deleteNode(struct Node *head, struct Node *n)
{
// When node to be deleted is head node
if (head == n)
{
n = head->next;
//Remove the link of next node
head->next = head->next->next;
return;
}
//When not first node, folow the normal deletion process
//Find the previous node
struct Node *prev = head;
while (prev->next != NULL && prev->next != n)
prev = prev->next;
// Check if node really exists in Linked List
if (prev->next == NULL)
{
cout << endl << "Given node is not present in Linked List";
return;
}
//Remove node from linked list should it exist
prev->next = prev->next->next;
return;
}
void display_list(student *t)
{
if (t == NULL)
cout << "List is Empty!";
else
{
while (t != NULL)
{
cout << "******Student******" << endl;
cout << t->st_ln() << endl;
cout << t->st_fn() << endl;
cout << t->st_score() << endl << endl;
t = t->nxt_ptr;
}
}
}
int main()
{
string ln, fn;
float s;
int n;
ifstream infile;
student *head = NULL; //pointer to a student object
student *cp = NULL; // pointer to end of the list
student *new_st = NULL; // pointer to a new student object
student *f = NULL; // pointer to found node
int option; // the numbe of menu item the user selects
infile.open("lab8d.txt");
while (!infile.eof())
{
infile >> fn >> ln >> s;
//instantiate a student object
new_st = new student;
//load the object with data
new_st->st_fn(fn);
new_st->st_ln(ln);
new_st->st_score(s);
// check for empty list - its a special case
if (head == NULL)
{
head = new_st;
cp = new_st;
}
else // list is not empty
{
cp->nxt_ptr = new_st;
cp = new_st;
}
} // end of loop
// loop to give the user some options
option = display_menu();
while (option != 5)
{
if (option == 1)
display_list(head);
else if (option == 2)
add_student(head);
else if (option == 3)
head = delete_front(head);
else if (option == 4)
{
f = search_last_name(head);
if (f != NULL)
{
cout << f->st_fn() << endl;
cout << f->st_ln() << endl;
cout << f->st_score() << endl;
cout << f->st_pass_or_fail() << endl;
}
else
cout << "Name not in the list" << endl;
}
else if (option == 6)
{
cout << "Enter the number of the node you would like to delete: " << endl;
cin >> n;
}
option = display_menu();
}
system("pause");
return 0;
}
The simpler and self-contained your functions are, the easier they are to test and debug, and the less like they are to fail.
Try something more like this:
Student.h:
#include <string>
class student_list;
class student
{
public:
student();
student(const std::string &fn, const std::string &ln, float s, student *nxt = NULL);
void next(student *s);
student* next() const;
void firstName(const std::string &fn);
std::string firstName() const;
void lastName(const std::string &ln);
std::string lastName() const;
void score(float s);
float score() const;
std::string pass_or_fail() const;
void display(bool showPassOrFail = false) const;
friend class student_list;
protected: // protected can be inherited
student *m_next;
std::string m_fn;
std::string m_ln;
float m_score;
};
Student.cpp:
#include "Student.h"
#include <iostream>
student::student()
: m_next(NULL), m_score(0)
{
}
student::student(const std::string &fn, const std::string &ln, float s, student *nxt)
: m_next(nxt), m_fn(fn), m_ln(ln), m_score(s)
{
}
void student::next(student *s)
{
m_next = s;
}
student* student::next() const
{
return m_next;
}
void student::firstName(const std::string &fn)
{
m_fn = fn;
}
std::string student::firstName() const
{
return m_fn;
}
void student::lastName(const std::string &ln)
{
m_ln = ln;
}
std::string student::lastName() const
{
return m_ln;
}
void student::score(float s)
{
m_score = s;
}
float student::score() const
{
return m_score;
}
std::string student::pass_or_fail() const
{
if (m_score >= 60)
return "PASSED";
else
return "FAILED";
}
void student::display(bool showPassOrFail) const
{
std::cout << lastName() << std::endl;
std::cout << firstName() << std::endl;
std::cout << score() << std::endl;
if (showPassOrFail)
std::cout << pass_or_fail() << std::endl;
}
StudentList.h:
#include <string>
class student;
class student_list
{
public:
student_list();
~student_list();
student* search_last_name(const std::string &ln);
student* insert(const std::string &fn, const std::string &ln, float s, student* after = NULL);
bool remove(int idx);
void display() const;
private:
student *m_head;
};
StudentList.cpp:
student_list::student_list()
: m_head(NULL)
{
}
student_list::~student_list()
{
while (m_head)
remove(0);
}
student* student_list::search_last_name(const std::string &ln)
{
student *t = m_head;
while (t)
{
if (t->lastName() == ln)
break; // found the last name
t = t->next();
}
return t;
}
student* student_list::insert(const std::string &fn, const std::string &ln, float s, student* after)
{
student **r;
if (after)
{
// add to list after the specified node
// get pointer to next node
r = &(after->m_next);
}
else
{
// add to the back of the list
// find pointer to last node
r = &m_head;
while (*r)
r = &((*r)->m_next);
}
// instantiate a new node
student *new_st = new student(fn, ln, s);
if (after)
new_st->next(*r);
// add to list
*r = new_st;
return new_st;
}
bool student_list::remove(int idx)
{
// delete a node at index
// find pointer to node
student **r = &m_head;
while ((*r) && (idx-- > 0))
r = &((*r)->m_next);
if (*r)
{
// delete node
student *t = *r;
*r = t->next();
delete t;
return true;
}
return false;
}
void student_list::display() const
{
student *t = m_head;
if (!t)
std::cout << "List is Empty!" << std::endl;
else
{
do
{
std::cout << "******Student******" << std::endl;
t->display();
t = t->next();
}
while (t);
}
}
Main.cpp:
#include "Student.h"
#include "StudentList.h"
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <limits>
#include <cstdlib>
int read_number()
{
int value;
while (!(std::cin >> value))
{
std::cout << "Must be a number, try again: ";
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
return value;
}
int display_menu()
{
int option;
std::cout << std::endl << std::endl;
std::cout << "1. Display List" << std::endl;
std::cout << "2. Add a student" << std::endl;
std::cout << "3. Delete first student" << std::endl;
std::cout << "4. Search by Last Name" << std::endl;
std::cout << "5. Delete student by index" << std::endl;
std::cout << "6. Exit" << std::endl << std::endl;
std::cout << "Choice: ";
do
{
option = read_number();
if ((option >= 1) && (option <= 6))
break;
std::cout << "Must be 1..6, try again: ";
}
while (true);
return (option != 6) ? option : -1;
}
int main()
{
student_list students;
std::ifstream infile("lab8d.txt");
if (infile.is_open())
{
student *cp = NULL;
std::string ln, fn;
float s;
while (infile >> fn >> ln >> s)
cp = students.insert(fn, ln, s, cp);
infile.close();
}
// loop to give the user some options
int option; // the number of menu item the user selects
while ((option = display_menu()) != -1)
{
switch (option)
{
case 1:
{
students.display();
break;
}
case 2:
{
// prompt for student info
std::string info;
std::cout << "Enter new student's first name, last name, and score: ";
std::string ln, fn;
float s;
if (std::cin >> fn >> ln >> s)
students.insert(fn, ln, s);
break;
}
case 3:
{
if (!students.remove(0))
std::cout << "List is empty" << std::endl;
break;
}
case 4:
{
// prompt for last name to search for
std::string ln;
std::cout << "Enter Last Name of the Student: ";
if (std::cin >> ln)
{
student *f = students.search_last_name(ln);
if (f)
f->display(true);
else
std::cout << "Name not found in List" << std::endl;
}
break;
}
case 5:
{
std::cout << "Enter the index of the Student to Delete: " << std::endl;
int idx = read_number();
if (!students.remove(idx))
std::cout << "Index not found in List" << std::endl;
break;
}
}
}
std::system("pause");
return 0;
}
That being said, you really should be using the std::list container instead, eg:
Student.h:
#include <string>
class student_list;
class student
{
public:
student();
student(const std::string &fn, const std::string &ln, float s);
void firstName(const std::string &fn);
std::string firstName() const;
void lastName(const std::string &ln);
std::string lastName() const;
void score(float s);
float score() const;
std::string pass_or_fail() const;
void display(bool showPassOrFail = false) const;
friend class student_list;
protected: // protected can be inherited
std::string m_fn;
std::string m_ln;
float m_score;
};
Student.cpp:
#include "Student.h"
#include <iostream>
student::student()
: m_score(0)
{
}
student::student(const std::string &fn, const std::string &ln, float s)
: m_fn(fn), m_ln(ln), m_score(s)
{
}
void student::firstName(const std::string &fn)
{
m_fn = fn;
}
std::string student::firstName() const
{
return m_fn;
}
void student::lastName(const std::string &ln)
{
m_ln = ln;
}
std::string student::lastName() const
{
return m_ln;
}
void student::score(float s)
{
m_score = s;
}
float student::score() const
{
return m_score;
}
std::string student::pass_or_fail() const
{
if (m_score >= 60)
return "PASSED";
else
return "FAILED";
}
void student::display(bool showPassOrFail) const
{
std::cout << lastName() << std::endl;
std::cout << firstName() << std::endl;
std::cout << score() << std::endl;
if (showPassOrFail)
std::cout << pass_or_fail() << std::endl;
}
Main.cpp:
#include "Student.h"
#include <list>
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <limits>
#include <algorithm>
#include <cstdlib>
int read_number()
{
int value;
while (!(std::cin >> value))
{
std::cout << "Must be a number, try again: ";
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
return value;
}
int display_menu()
{
int option;
std::cout << std::endl << std::endl;
std::cout << "1. Display List" << std::endl;
std::cout << "2. Add a student" << std::endl;
std::cout << "3. Delete first student" << std::endl;
std::cout << "4. Search by Last Name" << std::endl;
std::cout << "5. Delete student by index" << std::endl;
std::cout << "6. Exit" << std::endl << std::endl;
std::cout << "Choice: ";
do
{
option = read_number();
if ((option >= 1) && (option <= 6))
break;
std::cout << "Must be 1..6, try again: ";
}
while (true);
return (option != 6) ? option : -1;
}
int main()
{
std::list<student> students;
std::ifstream infile("lab8d.txt");
if (infile.is_open())
{
std::string ln, fn;
float s;
while (infile >> fn >> ln >> s)
students.push_back(student(fn, ln, s));
infile.close();
}
// loop to give the user some options
int option; // the number of menu item the user selects
while ((option = display_menu()) != -1)
{
switch (option)
{
case 1:
{
if (students.empty())
std::cout << "List is Empty!" << std::endl;
else
{
for(const auto &s : students)
{
std::cout << "******Student******" << std::endl;
s.display();
}
}
break;
}
case 2:
{
// prompt for student info
std::string info;
std::cout << "Enter new student's first name, last name, and score: ";
std::string ln, fn;
float s;
if (std::cin >> fn >> ln >> s)
students.push_back(student(fn, ln, s));
break;
}
case 3:
{
if (students.empty())
std::cout << "List is empty" << std::endl;
else
students.erase(students.begin());
break;
}
case 4:
{
// prompt for last name to search for
std::string ln;
std::cout << "Enter Last Name of the Student: ";
if (std::cin >> ln)
{
auto f = std::find(students.begin(), students.end(),
[&](const student &s){ return (s.lastName() == ln); }
);
if (f != students.end())
f->display(true);
else
std::cout << "Name not found in List" << std::endl;
}
break;
}
case 5:
{
std::cout << "Enter the index of the Student to Delete: " << std::endl;
int idx = read_number();
if ((idx < 0) || (idx >= students.size()))
std::cout << "Index not found in List" << std::endl;
else
students.erase(std::next(students.begin(), idx));
break;
}
}
}
std::system("pause");
return 0;
}
I just can't seem to figure out why my code doesn't work.
My program is about reading two text files representing a cardealership, and putting the input into a linked list or an STL list depending on mode. Then the orders are read and depending on the availability an error log is created.
The thng is that it keeps on looping in the linked list mode and that is doesn't seem to write the error log.
I feel pretty stupid about this. I don't want you guys to solve the error but teach me how to do it. I'm thankful for any review of my code by more experienced people.
I've tried debugging in Eclipse in XCode and in VS2012(VM with Win8). In none of the IDEs the variables are shown in the debug editor which I just don't understand. I use the MacOSX GCC Compiler.
So here are the txt files:
input.txt
Brera 3
Golf 5
Punto 13
Fiesta 19
and orders.txt
323 Brera 1
324 Golf 6
354 Punto 3
337 Gobldibock 1
this is my main method:
// file main.cpp
#include "cardealership.hpp"
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
int main( int argc, char* argv[] ) {
std::cout << "argv[2]: " << argv[2] << "\n";
std::cout << "argv[3]: " << argv[3] <<"\n";
const unsigned int mode = atoi( argv[1]);
std::string arg2 = argv[2];
std::string arg3 = argv[2];
cardealership* dealer = new cardealership(arg2, arg3, mode);
std::cout << "dealership created" << "\n";
dealer->readInputFileToList();
std::cout << "still running" << "\n";
dealer->readOutputFileAndAlterInventory();
std::cout << "finishing" << "\n";
return 0;
}
Here are the header of the class containing the actual lists:
// file cardealership.hpp
#ifndef CARDEALERSHIP_HPP // prevent multiple inclusions
#define CARDEALERSHIP_HPP
#include <string>
#include <list>
#include <vector>
typedef struct linkedNode
{
char* data; // will store information
int amountOfCars;
linkedNode* next; // the reference to the next node.
};
class cardealership
{
public:
cardealership (std::string inputFile, std::string ordersFile, const unsigned int mode);
~cardealership();
void readInputFileToList();
void readOutputFileAndAlterInventory();
void printInventory (); //TODO
private:
const unsigned int mode;
std::string inputFile;
std::string ordersFile;
std::list<linkedNode*> listOfCars; //Using Linked Node without linking them...
std::vector<linkedNode*> linkedListOfCars;
};
#endif
and the footer:
// file cardealership.cpp
#include "cardealership.hpp"
#include <iostream>
#include <cstring>
#include <fstream>
#include <sstream>
cardealership::cardealership(std::string inputFile, std::string ordersFile, const unsigned int mode)
: inputFile(inputFile),
ordersFile(ordersFile),
mode(mode)
{}
cardealership::~cardealership()
{
listOfCars.clear();
linkedListOfCars.clear();
}
void cardealership::readInputFileToList(){
std::ifstream infile;
std::string line;
infile.open(inputFile.c_str(),
std::ifstream::in);
if (!infile.good()){
std::cout << "Na na na Input File" << "\n";
}
linkedNode* previousNode;
while(getline(infile, line)){
char* model;
int amountOfCars;
linkedNode* tmpNode;
std::stringstream helperStream;
getline(infile, line);
helperStream << line;
helperStream >> model;
helperStream >> amountOfCars;
//Test
std::cout << "Line: " << line << std::endl;
std::cout << model << ", " << amountOfCars << std::endl;
tmpNode->data = model;
tmpNode->amountOfCars = amountOfCars;
if (mode == 0) { //Use linked list
if(previousNode != NULL){
previousNode->next = tmpNode; //Link that shit
previousNode = tmpNode;
linkedListOfCars.push_back(tmpNode);
}
else{
linkedListOfCars.push_back(tmpNode);
}
}
else if (mode == 1){ //Use STL list
listOfCars.push_back(tmpNode);
}
else{
std::cout<< "invalid mode" << std::endl;
}
if (infile.eof()){
break; // Not too nice but necessary because of last line problem
}
}
infile.close();
}
void cardealership::readOutputFileAndAlterInventory(){
std::ifstream infile;
std::string line;
infile.open(ordersFile.c_str(), std::ifstream::in);
if (!infile.good()){
std::cout << "Na na na Orders File" << "\n";
}
int id;
char* model;
int amountNeeded;
std::ofstream log("errorLog.txt");
if (!log.good()){
std::cout << "Na na na Log File" << "\n";
}
while (getline(infile, line)){
getline(infile, line);
std::stringstream helperStream;
helperStream << line;
helperStream >> id;
helperStream >> model;
helperStream >> amountNeeded;
if (mode == 0) { //Use linked list
linkedNode* tmpNode;
linkedNode* previousNode;
if (!linkedListOfCars.empty()){
tmpNode = linkedListOfCars.front();
while(tmpNode){
if (tmpNode->data == model) {
std::cout<< "Model found!" << std::endl;
}
if (tmpNode->amountOfCars > amountNeeded){
std::cout<< "Enough cars available!" << std::endl;
tmpNode->amountOfCars -= amountNeeded;
}
if (tmpNode->amountOfCars <= amountNeeded){ //
if (previousNode != NULL) {
linkedNode tmp3Node = *previousNode;
tmp3Node.next = tmpNode->next;
}
linkedNode* tmp2Node;
tmp2Node = tmpNode->next;
tmpNode = NULL;
tmpNode = tmp2Node;
//write error to log
log << "ID: "<< id << ", Not enough items!";
previousNode = tmpNode;
tmpNode = tmpNode->next;
}
}
if (!tmpNode) {
std::cout<< "Model not found." << std::endl;
//write error to log.
log << "ID: "<< id << ", Model not available!";
}
}
else{
std::cout<< "No cars to sell." << std::endl;
}
}
else if (mode == 1){ //Use STL list
if (!listOfCars.empty()) {
//Iterator copied and adapted from: http://www.cplusplus.com/reference/stl/list/begin/
std::list<linkedNode*>::iterator it;
for ( it=listOfCars.begin() ; it != listOfCars.end(); it++ ){
linkedNode* tmpNode = *it;
if (tmpNode->data == model) {
std::cout<< "Model found!" << std::endl;
}
if (tmpNode->amountOfCars >= amountNeeded){
std::cout<< "Enough cars available!" << std::endl;
tmpNode->amountOfCars -= amountNeeded;
}
if (tmpNode->amountOfCars < amountNeeded){
//delete entry and write error to log
it = listOfCars.erase(it);
log << "ID: "<< id << ", Not enough items!";
}
if (it++ == listOfCars.end()) {
//Write error to log if end of list is reached
log << "ID: "<< id << ", Model not available!";
}
}
}
else{
std::cout<< "No cars to sell." << std::endl;
}
}
else{
std::cout<< "Invalid mode." << std::endl;
}
}
infile.close();
}
void cardealership::printInventory (){
if (mode == 0) { //Use linked list
}
}
The post seems pretty long to me now but I hope I can still get some help...
Thanks in advance,
L
When adding a new linkedNode you declare a pointer to a node:
linkedNode* tmpNode;
The next mention of tmpNode is the following:
tmpNode->data = model;
However, tmpNode isn't a linkedNode, it's just a pointer to one. You're basically trying to save some data into space that other parts of your program may use. You need to make a linkedNode for tmpNode to point to so that it has its own storage. You may want to look into the new keyword.
This C++ program is created using Visual Studio 2010. It's a group project that has everyone in class stumped.
The program initially starts fine and the user can run through the program and add items that are written out to file. the items are read back in and displayed. When the user is done, on the program exiting return 0; it gives me "An unhandled exception of type System.AccessViolationException occurred. Attempted to read or write protected memory. This is often an indication that other memory is corrupt."
When this happens it opens up a file called utility here => for (_Iterator_base12 **_Pnext = &_Myproxy->_Myfirstiter; *_Pnext != 0; *_Pnext = (*_Pnext)->_Mynextiter) (*_Pnext)->_Myproxy = 0.
I can fix this by replacing return 0; with exit(0);
I know it's not a real fix though and just a band-aid over a bullet hole that is causing this issue.
After fixing (used very loosely here) that, then running the program again, it attempts to load the data file from the file system. It reads and loads the 1st item into a vector correctly but when it goes back to the start of the loop we see the same exception pop up, An unhandled exception of type System.AccessViolationException occurred.
This is the first project we have worked on using fstream and binary i/o. We had worked through a similar program that was just reading and writing strings w/out any issues.I believe that the issue stems from something in the fileHandler class but am having a difficult time pinpointing what is causing this issue.Any advice/help is greatly appreciated.Here is the code.stdafx.h
// stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
//
#pragma once
#include <stdio.h>
#include <iostream>
#include <stdlib.h>
#include <sstream>
#include <fstream>
#include <string.h>
#include <string>
#include <vector>
#include <time.h>
Week2.cpp (the main file for the project)
//Week2.cpp *******************
#include "stdafx.h"
#include "fileHandler.h"
using namespace std;
using namespace System;
int main(array<System::String ^> ^args)
{
fileHandler theFile("store.pkl");
vector<item> itemStack = theFile.getFile();
cout << "SKU Name Dept Vendor Max Order onHand" << endl;
cout << "-------------------------------------------" << endl;
for (int i = 0; i < itemStack.size(); i++)
{
cout << itemStack[i].toString() << endl;
}
vector<item> newStack;
//prompt for input
bool doneEditing = false;
while(!doneEditing)
{
int A;
int E;
int F;
int G;
string B;
string C;
string D;
string tempString;
cout << "Enter item info:" << endl << "Item SKU: ";
cin >> A;
cout << endl << "Item Name: ";
cin >> B;
cout << endl << "Item Dept: ";
cin >> C;
cout << endl << "Vendor Name: ";
cin >> D;
cout << endl << "Max Number: ";
cin >> E;
cout << endl << "Reorder Number: ";
cin >> F;
cout << endl << "OnHand Number: ";
cin >> G;
cout << endl << "Done?? Y/N: ";
cin >> tempString;
cout << endl;
item tempItem = item(A, B, C, D, E, F, G);
newStack.push_back(tempItem);
if (tempString == "Y" || tempString == "y")
{
doneEditing = true;
}
}
cout << "Saving stack to file" << endl;
theFile.putFile(newStack);
cout << "Items written to file" << endl;
vector<item> newFileStack = theFile.getFile();
cout << "After reload: " << endl;
cout << "SKU Name Dept Vendor Max Order onHand" << endl;
cout << "-------------------------------------------" << endl;
for (int i = 0; i < newFileStack.size(); i++)
{
cout << newFileStack[i].toString() << endl;
}
cout << "Thank you for using the Awesome Grocery Inventory Application" << endl;
system("PAUSE");
/*return 0; this breaks with same error as
when reading in saved file after application restart
*/
exit(0);
}
item.h
using namespace std;
#pragma once
class item
{
public:
item();
item(int sku, string name, string dept, string vendor, int max, int reorder, int onhand);
~item(void);
string toString();
int ItemSKU() const;
void ItemSKU(int val);
string ItemName() const;
void ItemName(string val);
string VendorName() const;
void VendorName(string val);
int MaxNumb() const;
void MaxNumb(int val);
int ReorderNumb() const;
void ReorderNumb(int val);
int OnHandNumb() const;
void OnHandNumb(int val);
private:
int itemSKU;
string itemName;
string itemDept;
string vendorName;
int maxNumb;
int reorderNumb;
int onHandNumb;
};
item.cpp
#include "StdAfx.h"
#include "item.h"
using namespace std;
item::item()
{
};
item::item(int sku, string name, string dept, string vendor, int max, int reorder, int onhand)
{
itemSKU = sku;
itemName = name;
itemDept = dept;
vendorName = vendor;
maxNumb = max;
reorderNumb = reorder;
onHandNumb = onhand;
}
item::~item(void)
{
}
string item::toString()
{
stringstream ss;
ss << itemSKU << "\t" << itemName << "\t" << itemDept << "\t" << vendorName << "\t" << maxNumb << "\t" << reorderNumb << "\t" << onHandNumb;
string s = ss.str();
return s;
}
int item::ItemSKU() const { return itemSKU; }
void item::ItemSKU(int val) { itemSKU = val; }
string item::ItemName() const { return itemName; }
void item::ItemName(string val) { itemName = val; }
string item::VendorName() const { return vendorName; }
void item::VendorName(string val) { vendorName = val; }
int item::MaxNumb() const { return maxNumb; }
void item::MaxNumb(int val) { maxNumb = val; }
int item::ReorderNumb() const { return reorderNumb; }
void item::ReorderNumb(int val) { reorderNumb = val; }
int item::OnHandNumb() const { return onHandNumb; }
void item::OnHandNumb(int val) { onHandNumb = val; }
fileHandler.h
#include "item.h"
using namespace std;
#pragma once
class fileHandler
{
public:
fileHandler(string);
~fileHandler(void);
vector<item> getFile();
void putFile(vector<item> &);
private:
string theFileName;
};
fileHandler.cpp
#include "stdafx.h"
#include "fileHandler.h"
using namespace std;
fileHandler::fileHandler(string name)
{
theFileName = name.c_str();
}
fileHandler::~fileHandler(void)
{
}
vector<item> fileHandler::getFile()
{
ifstream inFile;
string fileLine;
vector<item> localStack;
inFile.open(theFileName, ios::in|ios::binary);
if (inFile)
{
cout << "Getting file..." << endl;
cout << endl;
// not working on initial load if file is present at start
inFile.seekg(0);
while(!inFile.eof())
{
item tempItem;
inFile.read(reinterpret_cast< char * >(&tempItem), sizeof(item));
localStack.push_back(tempItem);
cout << "item added to stack" << endl;
} //breaks from here after reading in 1 item from saved file on reopen
} else {
ofstream newFile;
newFile.open(theFileName, ios::out|ios::binary);
newFile.close();
cout << "Creating new file..." << endl;
cout << endl;
inFile.open(theFileName, ios::in|ios::binary);
}
inFile.clear();
inFile.close();
if (localStack.size() > 0)
{
//removes some dirty data from end of stack
localStack.pop_back();
}
return localStack;
}
void fileHandler::putFile( vector<item> &items )
{
ofstream outFile;
outFile.open(theFileName, ios::out|ios::binary);
if(!outFile)
{
cerr<<"File could not be created"<<endl;
system("pause");
exit(1);
}
for (int i = 0; i < items.size(); i++)
{
outFile.write(reinterpret_cast<const char *>(&items[i]), sizeof(item));
}
outFile.clear();
outFile.close();
}
You cannot perform binary I/O this way with an object that contains std::string members. A std::string contains pointer(s) to dynamically allocated memory for its actual contents. You need to perform some type of serialization instead. The usual suggestion is Boost serialization.