Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I tried to print a array of characters using dynamic memory allocation with pointer. If i comment one pf the variables work, but when i tried to print both the program stop.
This is Main CPP.
#include <iostream>
#include "ContactInfo.h"
using namespace std;
int main() {
int n = 0;
char *ph, *nm;
ContactInfo *allcontacts;
cout << "How many people you want to add to phone book? ";
cin >> n;
allcontacts = new ContactInfo[n];
for (int i=0; i < n; i++) {
cout << i + 1 << ") Name: ";
cin >> nm;
allcontacts[i].setName(nm);
cout << i + 1 << ") Phone: ";
cin >> ph;
allcontacts[i].setPhone(ph);
}
cout << setw(8) <<"Name" << setw(8) << "Phone\n";
cout << "------------------------------------------------------\n";
for (int i=0; i < n; i++){
allcontacts[i].display();
}
return 0;
}
CPP
#include "ContactInfo.h"
void ContactInfo::setName(char *n) {
name = new char[strlen(n) + 1];
strcpy(name, n);
}
void ContactInfo::setPhone(char *p) {
phone = new char[strlen(p) + 1];
strcpy(phone, p);
}
ContactInfo::ContactInfo() {
// setName("");
// setPhone("");
}
ContactInfo::ContactInfo(char *n, char *p) {
setName(n);
setPhone(p);
}
ContactInfo::~ContactInfo() {
delete [] name;
delete [] phone;
name = nullptr;
phone = nullptr;
}
const char *ContactInfo::getName() const {
return name;
}
void ContactInfo::display() const {
cout << getName();
cout << getPhoneNumber();
cout << endl;
}
const char *ContactInfo::getPhoneNumber() const {
return phone;
}
HEADER
#include <iostream>
#include <cstring> // Needed for strlen and strcpy
using namespace std;
// ContactInfo class declaration.
class ContactInfo
{
private:
char *name; // The contact's name
char *phone; // The contact's phone number
public:
ContactInfo(char *, char *);
ContactInfo();
void setName(char *);
void setPhone(char *);
~ContactInfo();
const char *getName() const;
const char *getPhoneNumber() const;
void display() const;
};
Ouput
How many people you want to add to phonebook? 2
1) Name: www
1) Phone: 22
Process finished with exit code 0
You are mixing C and C++ code together. You have to use std::string for your input instead of char*. Try following code:
#include <iostream>
#include <vector>
#include <string>
#include <iomanip>
class ContactInfo {
private:
std::string name;
std::string phone;
public:
ContactInfo() {
}
ContactInfo(const std::string &Name, const std::string &Phone) {
name = Name;
phone = Phone;
}
void display() const {
std::cout << name << " " << phone << std::endl;
}
};
int main() {
int n = 0;
std::cout << "How many people you want to add to phone book? ";
std::cin >> n; std::cin.get();
std::vector<ContactInfo> all_contacts;
for (int i = 0; i < n; i++) {
std::string name, phone;
std::cout << i + 1 << ") Name: ";
std::cin >> name;
std::cout << i + 1 << ") Phone: ";
std::cin >> phone;
all_contacts.push_back(ContactInfo(name, phone));
}
std::cout << std::setw(8) << "Name" << std::setw(8) << "Phone" << std::endl;
std::cout << "------------------------------------------------------" << std::endl;
for (auto i : all_contacts) {
i.display();
}
return 0;
}
Related
i was using pointers and new operator for printing different city names. But the Microsoft Visual Studio show that it is Exception thrown:read access violation.
This happen even when i write *ptr=n; or *ptr=20; ,but works properly if i give ptr=&n; (if n is the variable with some value).
Program to display names of cities
#include <iostream>
#include <cstring>
using namespace std;
class city
{
protected:
char *name;
int len;
public:
char *s;
city();
~city();
void getdata()
{
s = new char[20];
cout << "enter the name of city" << endl;
cin >> s;
len = strlen(s);
name = new char[len + 1];
strcpy_s(name, 10, s);
}
void display()
{
cout << *name << endl;
}
private:
};
city::city()
{
len = 0;//initialization
name = NULL;
}
city::~city()
{
delete[]name;
delete[]s;
}
int main()
{
city *obj[10];
int n = 0;
int en=0;
do
{
obj[n] = new city;
obj[n]->getdata();
n++;
obj[n]->display();
cout << "do you want to enter another city?" << endl;
cout << "(enter 1 for yes and 0 for no"<<endl;
cin >> en;
} while (en);
delete[]obj;
system("pause");
return 0;
}
Screenshot of error
Don't manage memory manually! Use STL to forget memory manage!
#include <iostream>
#include <string>
#include <array>
class city
{
protected:
std::string name;
public:
city() = default;
//~city();
void getdata()
{
std::cout << "enter the name of city" << std::endl;
std::cin >> this->name;
}
void display()
{
std::cout << name << std::endl;
}
};
int main()
{
std::array<city, 10> obj;
for(auto&& o : obj)
{
o.getdata();
o.display();
std::cout
<< "do you want to enter another city?" << std::endl
<< "(enter 1 for yes and 0 for no" << std::endl;
int en=0;
std::cin >> en;
if(0 == en) return 0;
}
return 0;
}
https://wandbox.org/permlink/bz4iF3LNDSyUIZPb
I am trying to write a class with a map to keep a registry with unique ID for later accessing the objects. All compiled fine till i wrote the for loop in main trying to access objects of the class and their data. I am at a loss what is exactly wrong. I declared all static but doesn't work. I have been trying for several hours now but couldn't solve it. I know the problem is in the map as that is new for me, but i can't seem to find the issue. Hope someone sees what is wrong in my code.
#include <iostream>
#include <map>
#include <cassert>
#include <string>
#include <algorithm>
using namespace std;
class vertegenwoordiger{
public:
vertegenwoordiger(int id, string x, int y): ID(id), name(x),aantalpc(y) {
addtoregistry(this);
cout << "Vertegenwoordiger " << x << " is aangemaakt met " << y << " aantal verkochte pc's " << endl;
gemiddeldeverkoop = (gemiddeldeverkoop + y) / id;
}
static map<int, vertegenwoordiger*>registryMap; // PROBLEM HERE I GUESS
static void addtoregistry(vertegenwoordiger* object){
registryMap[object->ID] = object;
}
static void removefromregistry(vertegenwoordiger* object){
registryMap.erase(object->ID);
}
static vertegenwoordiger* findbymap(int id){
return registryMap[id];
} // MAYBE THIS FUNCTION IS NOT CORRECT ASWELL????
void commissionfixed (vertegenwoordiger* obj){
commissievast = obj->aantalpc*winstperpc;
}
void commissionextra (vertegenwoordiger*obj){
if (obj->aantalpc>gemiddeldeverkoop){
commissieplus = (obj->aantalpc - gemiddeldeverkoop) * 37;
}
}
static const int winstperpc;
static int gemiddeldeverkoop;
const int ID;
protected:
string name;
int aantalpc;
int commissievast;
int commissieplus;
};
const int vertegenwoordiger::winstperpc = 150;
int vertegenwoordiger::gemiddeldeverkoop = 0;
int main()
{
for (int i=0; i<4; i++){
string naam;
int pc;
cout << "geef naam in :";
cin >> naam;
cout << "geef aantal pc op :";
cin >> pc;
vertegenwoordiger* test = new vertegenwoordiger (i+1,naam,pc);
cout << "volgende aub : " << endl;
}
for (int i=1; i<4 ; i++){
vertegenwoordiger* val = vertegenwoordiger::findbymap(i); // I GUESS THE PROBLEM IS RELATED TO THIS LINE
vertegenwoordiger::commissionfixed (val);
vertegenwoordiger::commissionextra (val);
}
return 0;
}
#include <iostream>
#include <map>
#include <cassert>
#include <string>
#include <algorithm>
using namespace std;
class vertegenwoordiger{
public:
vertegenwoordiger(int id, string x, int y): ID(id), name(x),aantalpc(y){
addtoregistry(this);
cout << "Vertegenwoordiger " << x << " is aangemaakt met " << y << " aantal verkochte pc's " << endl;
gemiddeldeverkoop = (gemiddeldeverkoop + y) / id; }
static map<int, vertegenwoordiger*>registryMap;
static void addtoregistry(vertegenwoordiger* object){ registryMap[object->ID] = object; }
static void removefromregistry(vertegenwoordiger* object){ registryMap.erase(object->ID); }
static vertegenwoordiger* findbymap(int id){ return registryMap[id]; }
void commissionfixed (){
commissievast = this->aantalpc*winstperpc; }
void commissionextra (){
if (this->aantalpc>gemiddeldeverkoop){ commissieplus = (this->aantalpc - gemiddeldeverkoop) * 37; } }
void readCommission(){
cout << "comission payment is " << this->commissievast << endl;
}
static const int winstperpc;
static int gemiddeldeverkoop;
const int ID;
string name;
protected:
int aantalpc;
int commissievast;
int commissieplus;
};
map<int, vertegenwoordiger*>vertegenwoordiger::registryMap;
const int vertegenwoordiger::winstperpc = 150; int vertegenwoordiger::gemiddeldeverkoop = 0;
int main() {
for (int i=0; i<2; i++){ string naam; int pc; cout << "geef naam in :";
cin >> naam;
cout << "geef aantal pc op :";
cin >> pc;
vertegenwoordiger* test = new vertegenwoordiger (i+1,naam,pc);
cout << "next please : " << endl; }
for (int i=1; i<3 ; i++){
vertegenwoordiger* val = vertegenwoordiger::findbymap(i);
val->commissionfixed ();
val->commissionextra ();
val->readCommission ();
}
return 0; }
Compiles and everything except adding in a 'ship'
Constructor for ship
Ship::Ship(std::string name, int length, std::string show) {
std::string _name = name;
int _length = length;
std::string _show = show;
}
void Ships::buildShip() {
std::string name, show;
int length = 0;
std::cout << "What is the name of the ship? ";
std::cin >> name;
std::cout << "How long is the ship in feet? ";
std::cin >> length;
std::cout << "What show/movie is the ship from? ";
std::cin >> show;
std::cout << std::endl;
Ship ship(name, length, show);
addShip(ship);
}
void Ships::addShip(Ship &ship) {
ships.push_back(ship);
}
I'm sure it's something very obvious, I've searched the web and found nothing helpful. I only took snippets from my code if anything else is needed let me know. Thanks in advance!
/Ship.h
#pragma once
#include <string>
class Ship {
std::string _name;
int _length;
std::string _show;
public:
Ship(){
std::string name = _name;
int length = _length;
std::string show = _show;
};
Ship(std::string _name, int _length, std::string _show);
std::string getName();
int getLength();
std::string getShow();
};
/Ship.cpp
#include <string>
#include "Ship.h"
Ship::Ship(std::string name, int length, std::string show) {
std::string _name = name;
int _length = length;
std::string _show = show;
}
std::string Ship::getName() {
return _name;
}
int Ship::getLength() {
return _length;
}
std::string Ship::getShow() {
return _show;
}
/Ships.h
#pragma once
#include <vector>
#include "Ship.h"
class Ships {
std::vector<Ship> ships;
public:
void addShip(Ship &ship);
int getCount();
Ship getLongestShip();
void buildShip();
int getNumberOfShipsLongerThan(int input);
void displayShips();
};
/Ships.cpp
#include "Ships.h"
#include <iostream>
void Ships::addShip(Ship &ship) {
ships.push_back(ship);
}
int Ships::getCount() {
return ships.size();
}
Ship Ships::getLongestShip() {
Ship longestShip = ships[0];
for (Ship aShip : ships) {
if (longestShip.getLength() < aShip.getLength())
longestShip = aShip;
}
std::cout << "The longest ship is the " << longestShip.getName() << std::endl;
std::cout << "From end to end the length is " << longestShip.getLength() << std::endl;
std::cout << "The show/movie it is from is " << longestShip.getShow() << std::endl;
return longestShip;
}
int Ships::getNumberOfShipsLongerThan(int input) {
int longerThan = 0;
int size = ships.size();
for (int i = 0; i < size; i++) {
if (input < ships[i].getLength())
longerThan++;
}
return longerThan;
}
void Ships::displayShips() {
std::cout << " Complete Bay Manifest " << std::endl;
std::cout << "***********************" << std::endl;
for (int i = 0; i < ships.size(); i++) {
int a = i + 1;
std::cout << "Ship (" << a << ")" << std::endl;
std::cout << "Name: " << ships[i].getName() << std::endl;
std::cout << "Length: " << ships[i].getLength() << std::endl;
std::cout << "Show: " << ships[i].getShow() << std::endl<<std::endl;
}
}
void Ships::buildShip() {
std::string name, show;
int length = 0;
std::cout << "What is the name of the ship? ";
std::cin >> name;
std::cout << "How long is the ship in feet? ";
std::cin >> length;
std::cout << "What show/movie is the ship from? ";
std::cin >> show;
std::cout << std::endl;
Ship ship(name, length, show);
addShip(ship);
}
/driver.cpp
#include <iostream>
#include "Ship.h"
#include "Ships.h"
void menu();
Ship buildShip();
void shipsInBay(Ships &ships);
void processDirective(int choice, Ships &ships);
void longerThan(Ships &ships);
int main() {
std::cout << "Welcome to Daniel Mikos' Ship Bay!" << std::endl << std::endl;
menu();
system("PAUSE");
return 0;
}
void menu() {
Ships ships;
int choice = 0;
std::cout << "Please make a selection" << std::endl;
std::cout << " (1) Add a ship to the bay" << std::endl;
std::cout << " (2) How many ships are already in the bay?" << std::endl;
std::cout << " (3) Which ship is the longest? " << std::endl;
std::cout << " (4) Ships longer than ___? " << std::endl;
std::cout << " (5) Manifest of all ships currently logged" << std::endl;
std::cout << " (6) Exit" << std::endl;
std::cout << " Choice: ";
std::cin >> choice;
processDirective(choice, ships);
}
Ship buildShip() {
std::string name, show;
int length = 0;
std::cout << "What is the name of the ship? ";
std::cin >> name;
std::cout << "How long is the ship in feet? ";
std::cin >> length;
std::cout << "What show/movie is the ship from? ";
std::cin >> show;
std::cout << std::endl;
Ship ship(name, length, show);
return ship;
}
void shipsInBay(Ships &ships) {
int count = ships.getCount();
std::cout << std::endl;
std::cout << "There is currently " << count;
std::cout << " ship(s) in bay" << std::endl << std::endl;
}
void longerThan(Ships &ships) {
int input = 0;
std::cout << "Find ships longer than? ";
std::cin >> input;
std::cout << "There are " << ships.getNumberOfShipsLongerThan(input) << "longer than " << input << "feet";
}
void processDirective(int choice, Ships &ships) {
if (choice == 1)
buildShip();
if (choice == 2)
shipsInBay(ships);
if (choice == 3)
ships.getLongestShip();
if (choice == 4)
longerThan(ships);
if (choice == 5)
ships.displayShips();
menu();
}
There is all of my code
To add an object to a vector of objects use emplace_back() and pass the constructor arguments as arguments to emplace back. It will then build the object in place so call:
ships.emplace_back(name, length, show);
to construct your ship object in place. Your constructor also is incorrect as pointed out by #Kevin. You need to change it to:
this->_name = name;
this->_length = length;
this->_show = show;
assuming I've guessed your class design correctly.
EDIT
Tried to build a minimum example from this and this works fine for me:
Header.h
class Ship {
std::string _name;
int _length;
std::string _show;
public:
Ship();
Ship(std::string _name, int _length, std::string _show);
std::string getName();
int getLength();
std::string getShow();
};
class Ships {
public:
void addShip(Ship &ship);
void buildShip();
std::vector<Ship> ships;
};
and Source.cpp
#include "Header.h"
Ship::Ship(std::string name, int length, std::string show) {
this->_name = name;
this->_length = length;
this->_show = show;
}
void Ships::buildShip() {
std::string name = "Name";
std::string show = "Show";
int length = 0;
ships.emplace_back(name, length, show);
}
int main(int argc, char argv[])
{
Ships ships;
ships.buildShip();
std::cout << "Number of ships = " << ships.ships.size() << std::endl;
return 0;
}
Prints Number of ships = 1. Can you slim it down to something like this?
I'm trying to read names and ages from user, until user inputs "stop". Then just print all these values. Please help me , I'm just the beginner in C++
// Pass.cpp
// Reading names and ages from user and outputting them
#include <iostream>
#include <iomanip>
#include <cstring>
using std::cout;
using std::cin;
using std::endl;
using std::setw;
using std::strcmp;
char** larger(char** arr);
int* larger(int* arr);
void read_data(char*** names, int** ages);
void print_data(char*** names, int** ages);
int main()
{
char** names = new char*[5];
char*** p_names = &names;
int* ages = new int[5];
int** p_ages = &ages;
read_data(p_names,p_ages);
print_data(p_names,p_ages);
}
void read_data(char*** names, int** ages)
{
const char* sent = "stop";
const int MAX = 15;
int count = 0;
char UI[MAX];
cout << "Enter names and ages."
<< endl << "Maximum length of name is " << MAX
<< endl << "When stop enter \"" << sent << "\".";
while (true)
{
cout << endl << "Name: ";
cin.getline(UI,MAX,'\n');
if (!strcmp(UI, sent))
break;
if (count + 1 > sizeof (&ages) / sizeof (&ages[0]))
{
*names = larger(*names);
*ages = larger(*ages);
}
*names[count] = UI;
cout << endl << "Age: ";
cin >> *ages[count++];
}
}
void print_data(char*** names, int** ages)
{
for (int i = 0; i < sizeof(*ages) / sizeof(*ages[0]);i++)
{
cout << endl << setw(10) << "Name: " << *names[i]
<< setw(10) << "Age: " << *ages[i];
}
}
char** larger(char** names)
{
const int size = sizeof(names) / sizeof(*names);
char** new_arr = new char*[2*size];
for (int i = 0; i < size; i++)
new_arr[i] = names[i];
return new_arr;
}
int* larger(int* ages)
{
const int size = sizeof(ages) / sizeof(*ages);
int* new_arr = new int[2 * size];
for (int i = 0; i < size; i++)
new_arr[i] = ages[i];
return new_arr;
}
You are really over complicating things.
Given the original problem:
Write a program that reads a number (an integer) and a name (less than
15 characters) from the keyboard. Design the program so that the data
is done in one function, and the output in another. Store the data in
the main() function. The program should end when zero is entered for
the number. Think about how you are going to pass the data between
functions
The problem wants you to think about passing parameters to functions. A simple solution would be:
#include "stdafx.h"
#include <iostream>
#include <iomanip>
using namespace std;
// Pass in a char array and an integer reference.
// These values will be modified in the function
void read_data(char name[], int& age)
{
cout << endl << "Age: ";
cin >> age;
cin.ignore();
cout << endl << "Name: ";
cin.getline(name, 16);
}
// Pass a const array and an int value
// These values will not be modified
void print_data(char const *name, int age)
{
cout << endl << setw(10) << "Name: " << name
<< setw(10) << "Age: " << age;
}
int main()
{
char name[16];
int age;
cout << "Enter names and ages."
<< endl << "Enter 0 age to quit.";
do {
read_data(name, age);
print_data(name, age);
} while (0 != age)
}
EDIT: Modified per user3290289's comment
EDIT2: Storing data in an array
// Simplify by storing data in a struct (so we don't have to manage 2 arrays)
struct Person {
char name[16];
int age;
};
// Returns how many People were input
int read_data(Person*& arr)
{
int block = 10; // How many persons to allocate at a time
arr = NULL;
int arr_size = 0;
int index = 0;
while (true) {
if (index == arr_size) {
arr_size += block;
arr = (Person *)realloc(arr, arr_size * sizeof(Person)); // Reallocation
// Should check for error here!
}
cout << endl << "Age: ";
cin >> arr[index].age;
cin.ignore();
if (0 == arr[index].age) {
return index;
}
cout << endl << "Name: ";
cin.getline(arr[index++].name, 16);
}
}
void print_data(Person *arr, int count)
{
for (int i = 0; i < count; i++) {
cout << endl << setw(10) << "Name: " << arr[i].name
<< setw(10) << "Age: " << arr[i].age;
}
}
int main()
{
Person *arr;
int count = read_data(arr);
print_data(arr, count);
free(arr); // Free the memory
}
try this:
#include <iostream>
#include <iomanip>
#include <vector>
#include <sstream>
using std::cout;
using std::cin;
using std::endl;
using std::setw;
using std::strcmp;
void read_data(std::vector<std::string> &names, std::vector<int> &ages);
void print_data(std::vector<std::string> &names, std::vector<int> &ages);
int main()
{
std::vector<std::string> names;
std::vector<int> ages;
read_data(names, ages);
print_data(names, ages);
}
void read_data(std::vector<std::string> &names, std::vector<int> &ages)
{
const char* sent = "stop";
cout << "Enter names and ages."
<< endl << "When stop enter \"" << sent << "\".";
while (true)
{
std::string input;
cout << endl << "Name: ";
std::getline(cin, input);
if (!strcmp(input.c_str(), sent))
break;
names.push_back(input);
cout << endl << "Age: ";
std::string age;
std::getline(cin, age);
ages.push_back(atoi(age.c_str()));
}
}
void print_data(std::vector<std::string> &names, std::vector<int> &ages)
{
for (int i = 0; i < names.capacity() ; i++)
{
cout << endl << setw(10) << "Name: " << names.at(i)
<< setw(10) << "Age: " << ages.at(i);
}
}
One problem I see is this if statement:
if (count + 1 > sizeof (&ages) / sizeof (&ages[0]))
&ages is the address of an int**, a pointer, and so it's size is 8 (usually) as that is the size of a pointer type. The function does not know the size of the array, sizeof will only return the correct answer when ages is declared in the same scope.
sizeof(&ages) / sizeof(&ages[0])
will always return 1
I believe one natural solution about this problem is as follows:
create a "std::map" instance. Here std::map would sort the elements according to the age. Here my assumption is after storing the data into the container, you would like to find about a particular student age/smallest/largest and all various manipulation with data.Just storing and printing the data does not make much sense in general.
create a "std::pair" and take the both input from the user into the std::pair "first" and "second" member respectively. Now you can insert this "std::pair" instance value into the above "std::map" object.
While printing, you can now fetch the each element of "std::map" in the form of "std::pair" and then you can display pair "first" and "second" part respectively.
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.