I'm quite new to C++, I'm trying to achieve a task whereby i could read from a csv file and write to that same file and vice versa depending on the user's selection. This is what i did:
Here's the data already on file
1,Mickey,23,090,Girne,TRNC,465
2,Charles,23,090,Girne,TRNC,465
3,Species,23,090,Girne,TRNC,465
4,Moody,23,090,Girne,TRNC,465
5,Kpokiyo,23,090,Girne,TRNC,465
6,Sualp,23,090,Girne,TRNC,465
Here's the code i wrote so far
#include <iostream>
#include <sstream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
bool checkIsFile();
void addUser(string e[][7], int num);
void readAllUsers(string x[][7]);
void breakArray(string x[], string y[][7], int num);
bool checkAccout(string x[], int y, string search);
void findUser(string x[], string y[],string z[], string a[],string t[],
string c[], string d[]);
int findRowNumber();
int main()
{
int option;
int acc;
string emp[findRowNumber()][7];
string account[findRowNumber()], age[findRowNumber()],name[findRowNumber()],
state[findRowNumber()], city[findRowNumber()], phone[findRowNumber()],
zip[findRowNumber()];
//infinite loop
while(true){
cout<<"-------------------------\n";
cout<<"Menu Options\n";
cout<<"1 Add account\n";
cout<<"2 List Accounts\n";
cout<<"3 Delete account\n";
cout<<"4 Find user\n";
cout<<"5 Exit program\n";
cout<<"-------------------------\n";
cin>>option;
if(option==1)
{
readAllUsers(emp);
addUser(emp, findRowNumber());
}
else if(option==2)
{
readAllUsers(emp);
}
else if(option==3)
{
//delete a user;
}
else if(option==4)
{
//find user
readAllUsers(emp);
breakArray(account,emp,0);
breakArray(name,emp,1);
breakArray(age,emp,2);
breakArray(phone,emp,3);
breakArray(city,emp,4);
breakArray(state,emp,5);
breakArray(zip,emp,6);
findUser(account,name,age,phone,city,state,zip);
}
else if(option==5)
{
return 0;
}
else
{
cout<<"Invalid option\n";
}
}
}
void addUser(string e[][7], int num)
{
string emp[num + 1][7];
for(int a=0;a<num;a++)
{
for(int b=0;b<7;b++)
{
emp[a][b] = e[a][b];
}
}
//just to test if it works
emp[num][0] = "10";
emp[num][1] = "10";
emp[num][2] = "10";
emp[num][3] = "10";
emp[num][4] = "10";
emp[num][5] = "10";
emp[num][6] = "10";
ofstream inFile;
inFile.open("info.csv");
for(int a=0;a<num + 1;a++)
{
for(int b=0;b<7;b++)
{
cout<<emp[a][b];
}
}
for(int i=0;i<num +1; i++)
{
inFile << emp[i][0] + "," + emp[i][1] + "," + emp[i][2] + "," + emp[i][3] + "," + emp[i][4] + "," + emp[i][5] + "," + emp[i][6]<<endl;
}
inFile.close();
}
void readAllUsers(string x[][7])
{
ifstream inFile("info.csv");
string line;
int linenum = 0;
while (getline (inFile, line))
{
istringstream linestream(line);
string item;
int itemnum = 0;
while (getline (linestream, item, ','))
{
x[linenum][itemnum] = item;
itemnum++;
}
linenum++;
}
inFile.close();
}
void breakArray(string x[], string y[][7], int num)
{
for(int i=0;i<findRowNumber();i++)
{
for(int j=0;j<7;j++)
{
x[i] = y[i][num];
}
}
}
bool checkAccout(string x[], int y, string search)
{
bool check = false;
for(int i=0;i<y;i++)
{
if(x[i]==search)
{
check = true;
}
}
return check;
}
void findUser(string x[], string y[],string z[], string a[],
string t[], string c[], string d[])
{
string search;
bool check = false;
cout<<"Enter Account Number to Search: ";
cin>>search;
for(int i=0;i<findRowNumber();i++)
{
if(x[i]==search)
{
cout<<"Account Number: " + x[i]<<endl<<
"Name:\t\t" + y[i]<<endl<<
"Age:\t\t" + z[i]<<endl<<
"Phone:\t\t" + a[i]<<endl<<
"City:\t\t" + t[i]<<endl<<
"State:\t\t" + c[i]<<endl<<
"Zip:\t\t" + d[i]<<endl;
check = true;
}
}
if(!check)
cout<<"User does not exist"<<endl;
}
int findRowNumber()
{
ifstream inFile("info.csv");
string line;
int linenum = 0;
while (getline (inFile, line))
{
linenum++;
}
inFile.close();
return linenum;
}
It seems to work great when i choose to search for a user(selecting 4). However, the problem is when i try to write to file, it's works but when i try to do any other task like searching the user again or re-writing to file, the program crashes.
Please what i'm i doing wrong.
Thanks
Your emp string array in the main function is declared with the initial size of the file and never resized when you add more entries, hence the crash when it tries to read a bigger file into the old size of array.
Related
I am pulling names as strings from a file, create a Person *p object, and put it into an array.
Then to search the array for a name but when I try to fetch the name I get a segmentation fault.
Why is this segmentation fault happening, and what can I do to fix it?
#include <iostream>
#include <string>
using namespace std;
class Person {
private:
string firstName;
string lastName;
string phoneNumber;
public:
Person();
Person(string f, string l, string n);
~Person(void);
void setName()
{
}
string getFirstName()
{
return firstName;
}
string getLastName()
{
return lastName;
}
string getNumber() { return phoneNumber; }
void print();
};
Array creation.
{
ifstream file;
file.open("phonebook.txt");
if (!file.is_open()) //Check for File Error.
{
cerr << "Failed to open file" << endl;
exit(1);
}
//Get Array Size
string line;
while (getline(file, line))
{
count++;
}
file.close();
//Create an array
Person *arrList[count];
buildArray(arrList, count);
if (uInput == "a" || uInput == "A") //To add
{
int x = addPerson();
if (x == 1)
{
count++;
}
delete[] arrList;
}
void buildArray(Person *arr[], int size)
{
string f, l, n;
ifstream file;
file.open("phonebook.txt");
for (int i = 0; i < size; i++)
{
file >> f >> l >> n;
Person *p = new Person(f, l, n);
arr[i] = p;
delete p;
}
}
The search, This is the part that has the trouble. I have tried a few different things including creating 2 Persons, and comparing their parts but whenever it goes into the .h it can not return the name.
if (uInput == "s" || uInput == "S")
{ //To Search
string f, l;
cout << "Find Who (Firstname Lastname) " << endl;
cin >> f >> l;
Person *n = new Person(f, l, "");
int i = 0;
bool found = false;
while (i <= count && found == false)
{
Person *p = new Person("", "", "");
p = arrList[i];
if (p->getFirstName() == n->getFirstName() && p->getLastName() == n->getLastName())
{
arrList[i]->print();
found = true;
delete p;
delete n;
}
i++;
}
while (i == count && found == false)
{
cout << "No results found. " << endl;
found = true;
}
}
My professor has asked us to make a program that will take a user's input and continue reading until the end of input. Only then, can the program output what the user has typed.
Input should be based on video title, it's url, comments made on the video, length (in minutes), and rating (in *).
For example:
United Break Guitars, https://www.youtube.com/watch?v+5YGc4zOqozo, Great example of one person getting a giant company to listen, 4.5, ***, Space Versus Tabs, https://www.youtube.com/watch?v=SsoOG6ZeyUl, Decide for yourself: spaces or tabs?, 2.83, ****
Before inputting any video description, the user needs to specify a sorting method of three choices, Rating, Length, or title. I have completed most of the code and sort method asked by my professor (bubble sort), however when I ask the program to sort by title (which is the only one of the three options that is a string), it does not output correctly.
Here is my code:
#include <iostream>
#include <stdlib.h>
#include <cstring>
using namespace std;
#include "video.h"
int main()
{
string user, url, comment, title;
int rating;
double length;
int i = 0, last = 0;
Video *videoObj[100];
// specifies how the videos should be sorted
cin >> user;
cin.ignore();
while (getline(cin,title) ) {
getline(cin, url);
getline(cin, comment);
cin >> length;
cin >> rating;
cin.ignore();
videoObj[i] = new Video(title, url, comment, length, rating);
i++;
last++;
}
//------------------------------------------------------------------------
//--------------- Sorts the list based on rating (*) ---------------------
//------------------------------------------------------------------------
if(user=="rating"){
for(int i = 0; i < last - 1; i++){
for(int j = 0; j< last - i -1; j++){
if(videoObj[j +1]->Rating(videoObj[j])){
swap(videoObj[j], videoObj[j+1]);
}
}
}
}
//------------------------------------------------------------------------
//--------------- Sorts the list based on length -------------------------
//------------------------------------------------------------------------
if(user=="length"){
for(int i = 0; i < last - 1; i++){
for(int j = 0; j< last - i -1; j++){
if(videoObj[j +1]->Length(videoObj[j])){
swap(videoObj[j], videoObj[j+1]);
}
}
}
}
//------------------------------------------------------------------------
//--------------- Sorts the list based on title --------------------------
//------------------------------------------------------------------------
if(user=="title"){
for(int i = 0; i < last - 1; i++){
for(int j = 0; j< last - i -1; j++){
if(videoObj[j +1]->Title(videoObj[j])){
swap(videoObj[j], videoObj[j+1]);
}
}
}
}
for(int i= 0; i < last; i++){
videoObj[i]->print();
}
//delete[] videoObj;
return 0;
}
video.cpp:
#include <iostream>
#include <algorithm>
using namespace std;
#include "video.h"
Video::Video(string video_title, string video_link, string video_comment, double video_length, int video_number)
: title(video_title), link(video_link), comment(video_comment), length(video_length), rating(video_number)
{
m_title = title;
m_link = link;
m_comment = comment;
m_length = length;
m_rating = rating;
}
bool Video::Rating(Video *other)
{
if(m_rating > other-> m_rating){
return true;
}
else
{
return false;
}
}
bool Video::Length(Video *other2)
{
if(m_length > other2-> m_length){
return true;
}
else
{
return false;
}
}
bool Video::Title(Video *other3)
{
if(m_length > other3-> m_length){
return true;
}
else
{
return false;
}
}
void Video::print(){
string star;
switch(rating){
case 1:
star = "*";
break;
case 2:
star = "**";
break;
case 3:
star = "***";
break;
case 4:
star = "****";
break;
case 5:
star = "*****";
break;
}
cout << title << ", " << link << ", " << comment << ", " << length << ", " << star << endl;
}
video.h:
#ifndef VIDEO_H
#define VIDEO_H
using namespace std;
class Video {
public:
Video(string video_title, string video_link, string video_comment, double video_length, int video_number);
void print();
bool Rating(Video *other);
bool Length(Video *other2);
bool Title(Video *other3);
private:
string m_title;
string m_link;
string m_comment;
double m_length;
int m_rating;
string title;
string link;
string comment;
double length;
int rating;
};
#endif
I'm not exactly sure what I need to do to title to make it function correctly. I was thinking of comparing by strings, but again, not sure where to start.
Also, another question, how do I use delete[] videoObj;without getting an error?
Well this is wrong, just a typo probably
bool Video::Title(Video *other3)
{
if(m_length > other3-> m_length){
return true;
}
else
{
return false;
}
}
It should be m_title not m_length (probably)
bool Video::Title(Video *other3)
{
if(m_title > other3-> m_title){
return true;
}
else
{
return false;
}
}
Also this code can be simplified, the above can be written in one line
bool Video::Title(Video *other3)
{
return m_title > other3-> m_title;
}
if (xxx) return true; else return false; is exactly the same as return xxx;. Beginners often don't realise you can calculate with booleans in this is way.
Having trouble compiling program. Should read input from text file and store into a dynamic array of structure. I'm prettty sure my problem lies in the ipod_Initialize function. I'm not sure how to pass the dynamic array structure through the function.
#include <iostream>
#include <string>
#include <fstream>
# include <ctime>
using namespace std;
struct Song
{
string title;
string artist;
float size{};
};
int song_Count(string);
void ipod_Initialize(string, int, Song);
void show_playlist();
int main(char *argv[]) {
// argv is filename
int count = song_Count(argv[1]);
Song* songInfo = new Song[count];
ipod_Initialize(argv[1], count, *songInfo);
cout << songInfo[0].title;
delete[] songInfo;
return 0;
}
int song_Count(string fileName){
ifstream inFile;
string data;
int count = 0;
inFile.open(fileName);
if (!inFile.is_open()){
cout << "Error opening file" << endl;
return 0;
}
while(!inFile.eof()){
getline(inFile, data);
if (!data.empty()){
count++;
}
}
inFile.close();
count = count / 3 + 1;
return count;
}
void ipod_Initialize(string fileName, int count, Song* songInfo) {
string data;
ifstream inFile;
inFile.open(fileName);
for (int i = 0; i <= count; i++) {
getline(inFile, data);
if (!data.empty())
songInfo[i].title = data;
getline(inFile, data);
if (!data.empty())
songInfo[i].artist = data;
//getline(inFile, mem);
if (!data.empty())
inFile >> songInfo[i].size;
}
}
I keep getting an error of bad memory allocation. I've spent the whole night trying to find where I went wrong but I can't figure out what.
I've combed through every line but still nothing. Could it be that my program/laptop just isn't strong enough?
Any help would be extremely helpful. My head is ringing and I need some rest.
Here's my code:
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <vector>
#include <string>
#include <sstream>
using namespace std;
// struct to store word + count combinations
struct wordItem{
string word;
int count;
};
void getStopWords(char *ignoreWordFileName, vector<string>& _vecIgnoreWords);
bool isCommonWord(string word, vector<string>& _vecIgnoreWords);
void printTopN(wordItem wordItemList[], int topN);
void doubleArray(wordItem wordItemList[], int size);
int getTotalNumberNonCommonWords(wordItem wordItemList[], int size, int wordCount);
const int STOPWORD_LIST_SIZE = 50;
// ./a.out 10 HW1-HungerGames_edit.txt HW1-ignoreWords.txt
int main(int argc, char* argv[]){
vector<string> vecIgnoreWords(STOPWORD_LIST_SIZE);
// verify we have the correct # of parameters, else throw error msg & return
if (argc != 4){
cout << "Usage: ";
cout << argv[0] << " <number of words> <filename.txt> <ignorefilename.txt>"<< endl;
return 0;
}
//Set vector with stop words
getStopWords(argv[3], vecIgnoreWords);
//initialize struct array
int aSize = 100;
wordItem *theStructArray = new wordItem[aSize];
int counter = 0;
int doubleCount = 0;
//read main txt file
ifstream inFile(argv[1]);
if(inFile.is_open()){
string line;
string theWord;
//extract words from file
while(getline(inFile, line)){
istringstream iss(line);
//extract and analyze word
while(iss >> theWord){
if(!(isCommonWord(theWord, vecIgnoreWords))){
bool inStructArray = false;
int inStructPosition;
//search for word in Struct array
while (inStructArray == false){
for(int i=0; i<aSize; i++){
if (theWord == theStructArray[i].word){
inStructArray = true;
inStructPosition = i;
}
}
break;
}
//if word is in struct array
if (inStructArray == true){
theStructArray[inStructPosition].count++;
}
//else if it isn't
else{
//create new wordItem and add into struct
wordItem newWord;
newWord.word = theWord;
newWord.count = 1;
theStructArray[counter+(100*doubleCount)] = newWord;
counter++;
}
//if struct array hits maximum amount of elements,
if (counter == (aSize-1)){
doubleArray(theStructArray, aSize);
counter = 0;
doubleCount++;
aSize +=100;
}
}
}
}
inFile.close();
}
//Bubble sort masterArray
int bI, bJ, flag = 1;
wordItem bTemp;
for(bI=1; (bI <= aSize && flag); bI++){
flag = 0;
for(bJ=0; bJ<aSize; bJ++){
if(theStructArray[bJ+1].count > theStructArray[bJ].count){
bTemp = theStructArray[bJ];
theStructArray[bJ] = theStructArray[bJ+1];
theStructArray[bJ+1] = bTemp;
flag = 1;
}
}
}
//Print topN words
printTopN(theStructArray, atoi(argv[1]));
//print others
cout << "#" << endl;
cout << "Array doubled: " << doubleCount << endl;
cout <<"#" << endl;
cout << "Unique non-common words: "<< (aSize-100+counter)<<endl;
cout << "#"<<endl;
cout <<"Total non-common words: "<< getTotalNumberNonCommonWords(theStructArray, aSize, counter)<<endl;
return 0;
}
void getStopWords(char *ignoreWordFileName, vector<string>& _vecIgnoreWords){
ifstream inFile(ignoreWordFileName);
if(inFile.is_open()){
int a = 0;
string line;
while(getline(inFile, line)){
_vecIgnoreWords.insert(_vecIgnoreWords.begin() + a, line);
}
inFile.close();
}
return;
}
bool isCommonWord(string word, vector<string>& _vecIgnoreWords){
for(int i=0; i<STOPWORD_LIST_SIZE; i++){
if(word == _vecIgnoreWords.at(i)){
return true;
}
}
return false;
}
void printTopN(wordItem wordItemList[], int topN){
cout << endl;
for(int i=0; i<topN; i++){
cout<< wordItemList[i].count << '-' << wordItemList[i].word << endl;
}
return;
}
void doubleArray(wordItem wordItemList[], int size){
wordItem *tempArray = new wordItem[size+100];
for(int i=0; i<size; i++){
tempArray[i] = wordItemList[i];
}
delete [] wordItemList;
wordItemList = tempArray;
}
int getTotalNumberNonCommonWords(wordItem wordItemList[], int size, int wordCount){
int total = 0;
for(int i=0; i<(size-100+wordCount); i++){
total+=wordItemList[i].count;
}
return total;
}
You are doing very bad things in void doubleArray(wordItem wordItemList[], int size)
you can call delete [] on the array if you pass an array, but you cannot change its value, so doubleArray(theStructArray, aSize); will cause theStructArray to be deleted but not assigned to the memory you allocated. You are just assigning the local variable in the function doubleArray
It is similar to:
void doubleit(int x)
{
x *= 2;
}
int y=3;
doubleit(y);
here x was momentarily doubled to 6, but y never changed.
you need to use references, or better make theStructArray a std::vector and be done with it.
In my program i got "corruption of heap" error
"Windows has triggered a breakpoint in Project_Name.exe.
This may be due to a corruption of the heap, which indicates a bug in JPS.exe or any of the DLLs it has loaded.
This may also be due to the user pressing F12 while Project_Name.exe has focus.
The output window may have more diagnostic information."
Here are the codes:
Header.h
#pragma once
#include <math.h>
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <string>
#include <stdio.h>
#include <stack>
#include <vector>
#include <ctime>
#include <cassert>
#include <cmath>
using namespace std;
class ClientInfo
{
public:
int dayM;
string monthM;
int dayL;
string monthL;
string fName, lName;
double itmAmt;
ClientInfo* next;
};
class Record
{
private:
int numOfClients;
public:
int returnNumOfClients();
ClientInfo* head;
Record();
Record* InitializeRecord();
char* CalculateMaturity();
string ViewClient();
Record* FindName(string nn, ClientInfo *xxx);
void SaveRecord(ClientInfo* h);
double ComputeBalance(double amount, string mnthL, int dyL, string mnthM, int dyM);
ClientInfo* AddClient(string fn,string ln,string xMonthL, int xDayL, string
xMonthM, int xDayM ,double xItemAmt);
ClientInfo* SearchClient(string n);
void RemoveItem(ClientInfo* h, ClientInfo* rc, string remfname);
bool CheckExistence(ClientInfo* hx, string fnx, string lnx);
template <typename T>
string numToStr ( T num )
{
stringstream ss;
ss << num;
return ss.str();
}
};
Record::Record():numOfClients(0),head(NULL)
{
}
Record* Record::FindName(string nn, ClientInfo * xxx)
{
ClientInfo* newci = new ClientInfo();
Record* newrec = new Record();
ClientInfo* node= xxx;
do{
if(node->lName==nn)
{
newrec->head=newrec->AddClient(node->fName,
node->lName,
node->monthL,
node->dayL,
node->monthM,
node->dayM,node->itmAmt);
}
node=node->next;
}while(node!=NULL);
return newrec;
}
int Record::returnNumOfClients()
{
return numOfClients;
}
void Record::SaveRecord(ClientInfo* h)
{
Record *rec = new Record();
ClientInfo* saveRec = h;
string str;
vector<string> v;
ofstream outF;
outF.open("Record.txt");
if(saveRec!=NULL)
{
do
{
str = saveRec->fName+'-'+saveRec->lName+'-'+
rec->numToStr(saveRec->monthL)+'-'+
rec->numToStr(saveRec->dayL)+'-'+
rec->numToStr(saveRec->monthM)+'-'+
rec->numToStr(saveRec->dayM)+'-'+
rec->numToStr(saveRec->itmAmt);
saveRec = saveRec->next;
v.push_back(str);
}
while(saveRec != NULL);
for(vector<string>::iterator it = v.begin(); it != v.end(); ++it)
{
if( it != v.begin())
outF<<'\n';
outF<< *it;
}
}
else
numOfClients=0;
outF.close();
}
char* Record::CalculateMaturity()
{
try
{
ClientInfo* saveRec = new ClientInfo();
Record* rec = new Record();
string str;
stack<string> month;
month.push("December");
month.push("November");
month.push("October");
month.push("September");
month.push("August");
month.push("July");
month.push("June");
month.push("May");
month.push("April");
month.push("March");
month.push("February");
month.push("January");
month.push("December");
month.push("November");
month.push("October");
month.push("September");
month.push("August");
month.push("July");
month.push("June");
month.push("May");
month.push("April");
month.push("March");
month.push("February");
month.push("January");
stack<string> mnth;
mnth.push("December");
mnth.push("November");
mnth.push("October");
mnth.push("September");
mnth.push("August");
mnth.push("July");
mnth.push("June");
mnth.push("May");
mnth.push("April");
mnth.push("March");
mnth.push("February");
mnth.push("January");
mnth.push("December");
mnth.push("November");
mnth.push("October");
mnth.push("September");
mnth.push("August");
mnth.push("July");
mnth.push("June");
mnth.push("May");
mnth.push("April");
mnth.push("March");
mnth.push("February");
mnth.push("January");
const char *delimeter="-";
char* date=new char;
time_t now = time(0);
struct tm tstruct;
char buf[80];
tstruct = *localtime(&now);
strftime(buf, sizeof(buf), "%m-%d", &tstruct);
date = buf;
char* token= new char;
vector<string> dt;
token=strtok(date,delimeter);
while(token!=NULL)
{
dt.push_back(token);
token=strtok(NULL,delimeter);
}
string monthL,monthM;
int dayL;
int monthnum;
istringstream(dt[0])>>monthnum;
for(int x=1;x!=monthnum;x++)
mnth.pop();
monthL=mnth.top();
istringstream (dt[1])>>dayL;
do{month.pop();}while(monthL!=month.top());
month.pop();
month.pop();
month.pop();
monthM=month.top();
str=monthL+'-'+
rec->numToStr(dayL)+'-'+
monthM+'-'+
rec->numToStr(dayL);
int strsize = str.size();
char* chr = new char;
for(int x=0;x<strsize;x++)
{
chr[x]=str[x];
}
return chr;
}
catch(char* ex){system("pause");}
}
ClientInfo* Record::AddClient(string fn, string ln,string xMonthL, int xDayL, string
xMonthM, int xDayM, double xItemAmt)
{
ClientInfo* newInfo = new ClientInfo();
Record* newRecord = new Record();
newInfo->fName = fn;
newInfo->lName = ln;
newInfo->dayM = xDayM;
newInfo->monthM = xMonthM;
newInfo->dayL = xDayL;
newInfo->monthL = xMonthL;
newInfo->itmAmt = xItemAmt;
if(newInfo->next!=NULL)
{
newInfo->next = head;
numOfClients++;
head = newInfo;
}
else
{
newInfo->next=NULL;
}
return head;
}
Record* Record::InitializeRecord()
{
Record* initRec = new Record();
ClientInfo* initClient = new ClientInfo();
ifstream inF;
inF.open("Record.txt");
char* rec;
char* token;
vector<string> v;
int dayL, dayM;
string monthL, monthM;
double itmAmt;
if(inF.good())
{
do
{
rec = new char;
token = new char;
inF>>rec;
token = strtok(rec,"-");
while(token!=NULL)
{
v.push_back(token);
token = strtok(NULL,"-");
}
istringstream(v[2])>>monthL;
istringstream(v[3])>>dayL;
istringstream(v[4])>>monthM;
istringstream(v[5])>>dayM;
istringstream(v[6])>>itmAmt;
initRec->AddClient(v[0],v[1],monthL,dayL,monthM,dayM,itmAmt);
v.erase(v.begin(),v.end());
}while(!inF.eof());
}
inF.close();
return initRec;
}
void Record::RemoveItem(ClientInfo* h, ClientInfo* rc, string remfname)
{
ClientInfo* head = h;
ClientInfo* temp = rc->next;
if(temp!=NULL)
{
rc->fName = rc->next->fName;
rc->lName = rc->next->lName;
rc->monthL = rc->next->monthL;
rc->dayL = rc->next->dayL;
rc->monthM = rc->next->monthM;
rc->dayM = rc->next->dayM;
rc->itmAmt = rc->next->itmAmt;
rc->next = temp->next;
numOfClients--;
free(temp);
}
else
{
head = NULL;
free(temp);
}
SaveRecord(head);
}
ClientInfo* Record::SearchClient(string n)
{
ClientInfo* current = head;
for(int x=numOfClients-1;current!=NULL;x--)
{
if(current->lName == n)
return current;
else
current = current->next;
}
return current;
}
string Record::ViewClient()
{
string s;
ClientInfo* itr;
itr = head;
if(numOfClients!=0)
{
for(int i = 0; i<returnNumOfClients();i++)
{
string empty = "";
int y = i+1;
s+="\n\n***************\nName: "+itr->fName+" "+itr->lName+"\n-----
----------\n"+
"Loan Origination Date: "+numToStr(itr->monthL)+"
"+numToStr(itr->dayL)+
"\n---------------\n"+"Date Of Maturity: "+numToStr(itr-
>monthM)+" "+numToStr(itr->dayM)+"\n---------------\n"+
"Balance: "+numToStr(itr->itmAmt);
itr = itr->next;
}
s.append("\n***************\n\n");
}
else
s ="There is no recorded client yet.\n\n";
return s;
}
double Record::ComputeBalance(double amount, string mnthL, int dyL, string mnthM, int
dyM)
{
try
{
double INTEREST = 0.04;
double PENALTY = 0.02;
stack<string> monthl;
monthl.push("December");
monthl.push("November");
monthl.push("October");
monthl.push("September");
monthl.push("August");
monthl.push("July");
monthl.push("June");
monthl.push("May");
monthl.push("April");
monthl.push("March");
monthl.push("February");
monthl.push("January");
monthl.push("December");
monthl.push("November");
monthl.push("October");
monthl.push("September");
monthl.push("August");
monthl.push("July");
monthl.push("June");
monthl.push("May");
monthl.push("April");
monthl.push("March");
monthl.push("February");
monthl.push("January");
stack<string> monthm;
monthm.push("December");
monthm.push("November");
monthm.push("October");
monthm.push("September");
monthm.push("August");
monthm.push("July");
monthm.push("June");
monthm.push("May");
monthm.push("April");
monthm.push("March");
monthm.push("February");
monthm.push("January");
monthm.push("December");
monthm.push("November");
monthm.push("October");
monthm.push("September");
monthm.push("August");
monthm.push("July");
monthm.push("June");
monthm.push("May");
monthm.push("April");
monthm.push("March");
monthm.push("February");
monthm.push("January");
int ml=0;
int mm=0;
do{
monthl.pop();
mm++;
}while(mnthL!=monthl.top());
do
{
monthm.pop();
ml++;
}while(mnthM!=monthm.top());
int diff=abs(mm-ml);
double balance=diff*(amount*(INTEREST+
(INTEREST/(pow(INTEREST+1,diff)-1))));
return balance;
}
catch(double ex){system("pause");}
}
bool Record::CheckExistence(ClientInfo* hx, string fnx, string lnx)
{
ClientInfo *hh;
hh = head;
int t=0;
for(int x=numOfClients; hh!=NULL && x!=0; x--)
{
if(hh->fName == fnx && hh->lName==lnx)
t++;
else
hh=hh->next;
}
if(t!=0)
return true;
else
return false;
}
Main.cpp
#include "Header.h"
int main()
{
Record* rec = new Record();
ClientInfo* info;
Record* samelastrec = new Record();
double amt;
double balance;
int number;
int choose;
char ch;
double principal;
string iLName,iFName;
string nn;
int iDayL,iDayM;
string iMonthL,iMonthM;
string delfname;
rec=rec->InitializeRecord();
again:
system("cls");
cout<<"WELCOME TO JEWELRY PAWNING SYSTEM."<<endl;
cout<<"\n(1)Add Client\n(2)Remove Client\n(3)Search Client\n\n->";
cin>>choose;
Record *find = new Record();
ClientInfo* found;
system("cls");
int search;
char* datelm;
char* token;
vector<string> date;
string nnx;
switch(choose)
{
case 1:
system("cls");
if(rec->returnNumOfClients()!=0 || rec->returnNumOfClients()!=NULL)
{
cout<<"First Name: ";
cin>>iFName;
cout<<"Last name: ";
cin>>iLName;
if(!rec->CheckExistence(rec->head,iFName,iLName))
{
cout<<"Amount: ";
cin>>amt;
datelm=rec->CalculateMaturity();
token=strtok(datelm, "-");
while(token!=NULL)
{
date.push_back(token);
token=strtok(NULL, "-");
}
istringstream(date[0])>>iMonthL;
istringstream(date[1])>>iDayL;
istringstream(date[2])>>iMonthM;
istringstream(date[3])>>iDayM;
balance=rec->ComputeBalance(amt,iMonthL,iDayL,iMonthM,iDayM);
istringstream(rec->numToStr(balance));
rec->head=rec>AddClient(iFName,iLName,iMonthL,iDayL,iMonthM,iDayM,balance);
system("pause");
}
else
{
cout<<"Member already exist!"<<endl;
system("pause");
}
}
else
{
cout<<"First Name: ";
cin>>iFName;
cout<<"Last name: ";
cin>>iLName;
cout<<"Amount: ";
cin>>amt;
datelm=rec->CalculateMaturity();
token=strtok(datelm, "-");
while(token!=NULL)
{
date.push_back(token);
token=strtok(NULL, "-");
}
istringstream(date[0])>>iMonthL;
istringstream(date[1])>>iDayL;
istringstream(date[2])>>iMonthM;
istringstream(date[3])>>iDayM;
balance=rec->ComputeBalance(amt,iMonthL,iDayL,iMonthM,iDayM);
istringstream(rec->numToStr(balance));
rec->head=rec>AddClient(iFName,iLName,iMonthL,iDayL,iMonthM,iDayM,balance);
system("pause");
}
rec->SaveRecord(rec->head);
goto again;
break;
case 2:
system("cls");
find->head = rec->head;
cout<<"Enter Last Name: ";
cin>>iLName;
samelastrec=new Record();
samelastrec=samelastrec->FindName(iLName, rec->head);
if(find->SearchClient(iLName) == NULL)
{
cout<<"Client not found.\n";
system("pause");
}
else
{
found = find->SearchClient(iLName);
if(samelastrec->returnNumOfClients()>1)
{
cout<<samelastrec->ViewClient()<<endl<<endl;
cout<<"There are "<<samelastrec->numToStr(samelastrec->returnNumOfClients())
<<" Clients with "<<samelastrec->head->lName<<" last name";
cout<<endl<<"Enter the first name of the client you want to
remove: ";
cin>>delfname;
system("cls");
if(samelastrec->CheckExistence(samelastrec->head,delfname,
iLName))
{
cout<<endl<<"Do you want to remove "<<delfname<<"
<<samelastrec->head->lName<<" ?(Y/N)";
cin>>ch;
if(ch=='Y' || ch=='y')
{
rec->RemoveItem(rec->head,found,delfname);
cout<<"Client Removed."<<endl;
system("cls");
}
else if(ch=='N' || ch=='n')
goto again;
}
else
{
cout<<"The member with "<<delfname<<" does not
exist."<<endl;
system("pause");
goto again;
}
system("pause");
}
else
{
cout<<endl<<samelastrec->ViewClient()<<endl;
cout<<"Remove Client? [Y/N]: ";
cin>>ch;
if(ch=='Y' || ch=='y')
{
system("cls");
rec->RemoveItem(rec->head,found,found->fName);
cout<<"Client Removed."<<endl;
system("pause");
}
else if(ch=='N' || ch=='n')
goto again;
}
}
goto again;
break;
case 3:
system("cls");
cout<<"Enter Last Name : ";
cin>>nnx;
samelastrec=new Record();
samelastrec=samelastrec->FindName(nnx, rec->head);
cout<<samelastrec->ViewClient()<<endl;
system("pause");
break;
case 4:
system("cls");
cout<<rec->ViewClient();
system("pause");
goto again;
break;
case 5:
cout<<"Number of clients: "<<rec->numToStr(rec->returnNumOfClients())
<<endl;
system("pause");
break;
default:
if(choose!=0)
{
cout<<"\n\nInvalid Entry.\n\n";
system("pause");
goto again;
}
else
{
cout<<"\n\nTHANK YOU FOR USING THE JEWELRY PAWNING SYSTEM!\n\n";
system("pause");
exit(1);
}
}
goto again;
system("pause");
return 0;
}
I can't figure out why I'm getting these errors.
Please help me debug this error.
Thanks!
Throughout your code you have sections like this that trash memory you do not own:
int strsize = str.size();
char* chr = new char;
for(int x=0;x<strsize;x++)
{
chr[x]=str[x];
}
return chr;
It looks like you don't quite understand how pointers and new work. new char; allocates enough memory for just one character - typically one byte; so when x is larger than 0 in the subsequent loop you're overwriting memory you do not own, leading eventually to a crash. You have a number of sections of code like this. Either allocate the correct amount of memory for the operation (e.g. new char[strsize]), or (preferably) use C++ strings instead of character arrays.
(I also note you do not appear to ever free any of the memory you allocate, this will eventually cause problems as you perform more allocations during a run of the program. In general, every use of new should be matched by a corresponding use of delete).