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).
Related
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.
The while loop in the code gives segmentation fault(because tempiq is NULL).I can't figure out why tempiq is NULL when iqueue->front is displaying proper values and is not null(for sure).
//......previous code
tempiq=iqueue->front;
cout<<"\n"<<iqueue->front->link<<""<<iqueue->front;
if(tempiq)// && iqueue->front)
cout<<"\n aaaaaaaaaaaaaaaaaaaa\t";
while(tempiq)
{
//....rest of code
The full code for reference is given below:(the above code segment is in the main function at the last)
#include <vector>
#include <iostream>
#include <string.h>
#include <fstream>
#include <stdio.h>
#include <termios.h>
#include <sstream>
#include <unistd.h>
#include <cstdlib>
#include <ctype.h>
using namespace std;
#define NO_OF_CHARS 256
/* This function builds the TF table which represents Finite Automata for a
given pattern */
void computeTransFun(char *pat, int M, int TF[][NO_OF_CHARS])
{
int i, lps = 0, x;
// Fill entries in first row
for (x =0; x < NO_OF_CHARS; x++)
TF[0][x] = 0;
TF[0][pat[0]] = 1;
// Fill entries in other rows
for (i = 1; i<= M; i++)
{
// Copy values from row at index lps
for (x = 0; x < NO_OF_CHARS; x++)
TF[i][x] = TF[lps][x];
// Update the entry corresponding to this character
TF[i][pat[i]] = i + 1;
// Update lps for next row to be filled
if (i < M)
lps = TF[lps][pat[i]];
}
}
/* Prints all occurrences of pat in txt */
int searchauto(char *pat, char *txt)
{
int M = strlen(pat);
int N = strlen(txt);
int TF[M+1][NO_OF_CHARS];
computeTransFun(pat, M, TF);
int flag=0;
// process text over FA.
int i, j=0;
for (i = 0; i < N; i++)
{
j = TF[j][txt[i]];
if (j == M)
{
return flag;
//printf ("\n pattern found at index %d", i-M+1);
}
}
return flag;
}
class Node
{
char content;
bool marker;
vector <Node*>children;
public:
Node(){ content='\0'; marker=false; }
~Node(){}
void setContent(char c){content=c; }
void setMarker(){this->marker=true; }
char getContent(){return content; }
bool getMarker(){return marker; }
Node *findChild(char c);
void appendChild(Node *child)
{ children.push_back(child); }
vector<Node *> getChildren()
{ return children; }
};
class Trie
{
public:
Node *root;
int abc;
void addWord(string s);
void deleteWord(string s);
bool searchWord(string s);
Trie(){ root=new Node(); }
~Trie(){}
};
Node *Node::findChild(char c)
{
for(int i=0; i< children.size(); i++)
{
Node *temp=children.at(i);
if(temp->content==c)
return temp;
}
return NULL;
}
void Trie:: addWord(string s)
{
//cout<<"\naddword called for "<<s<<"::::::::::::::::::::::::\n";
Node *current=root;
if(s.length()==0)
{ cout<<"\txxxx\t"; current->setMarker(); return ; }
for(int i=0;i<s.length();i++)
{
Node *child=current->findChild(s[i]);
if(child!=NULL)
current=child;
else
{
Node *tmp=new Node();
tmp->setContent(s[i]);
current->appendChild(tmp);
current=tmp;
}
if(i==s.length()-1)
current->setMarker();
cout<<"\ttrying\t";
}
cout<<"\n word added\t";
}
bool Trie::searchWord(string s)
{
cout<<"\nsearchWord called for "<<s<<endl;
Node *current=root;
cout<<"\n search started\t";
cout<<endl;
while(current !=NULL)
{
cout<<"\t00\t";
for(int i=0;i<s.length();i++)
{
cout<<s[i]<<" ";
Node *temp=current->findChild(s[i]);
if(temp==NULL)
return false;
current=temp;
}
cout<<endl;
int a;
// cin>>a;
if(current->getMarker())
{
cout<<"String found......................................................................................................\n";
return true;
}
else
{
cout<<"Sorry string not found in trie....................................................................................\n";
return false;
}
}
}
struct node
{
struct node *next;
int rank;
int nopage;
Trie *trie;
string value;
};
struct indexqueue
{
struct indexnode *front;
struct indexnode *rear;
};
struct indexqueue *createindexqueue()
{
struct indexqueue *temp=new indexqueue;
temp->front=NULL;
temp->rear=NULL;
//temp->count=0;
return temp;
}
struct indexnode
{
int id;
int rank;
int *point2[];
string link;
Trie *down;
struct indexnode *next;
};
struct indexnode *createindexnode(string val)
{
struct indexnode *temp=new indexnode;
temp->next=NULL;
//temp->value=val;
//cout<<"Node created with val: "<<val<<endl;
return temp;
}
struct indexqueue *iqueue;
struct queue
{
struct node *front;
struct node *rear;
int count;
};
struct node *createnode(string val)
{
struct node *temp=new node;
temp->next=NULL;
temp->value=val;
//cout<<"Node created with val: "<<val<<endl;
return temp;
}
struct queue *createqueue()
{
struct queue *temp=new queue;
temp->front=NULL;
temp->rear=NULL;
temp->count=0;
return temp;
}
struct queue *pop(struct queue *queue1)
{
struct node *temp=new node;
if(queue1->front==NULL)
return NULL;
else if(queue1->front==queue1->rear)
{
queue1->front=NULL;
queue1->rear=NULL;
}
else
{
queue1->front=queue1->front->next;
}
return queue1;
}
struct queue *push(string val, struct queue *queue1)
{
struct node *new1=createnode(val);
if(queue1->front==NULL && queue1->rear==NULL)
{
queue1->front=queue1->rear=new node;
queue1->rear=new1;
queue1->front=new1;
//cout<<"1\n";
}
else
{
queue1->rear->next=new node;
queue1->rear->next=new1;
queue1->rear=queue1->rear->next;
//cout<<"2\n";
}
queue1->count++;
return queue1;
}
void inserttrie(struct queue *queue1,string value,string collection[],int n)
{
struct node *temp=queue1->front;
while(temp!=NULL)
{
if(temp->value.compare(value)==0)
{
temp->nopage=n;
for(int i=0;i<n;i++)
temp->trie->addWord(collection[i]);
}
}
}
void display(struct queue *queue1)
{
if(!queue1->front)
{
cout<<"Queue empty\n";
return;
}
struct node *temp=queue1->front;
while(temp)
{
cout<<temp->value<<"\n";
temp=temp->next;
}
}
void pushindex(struct indexnode *temp)
{
if(iqueue->front==NULL && iqueue->rear==NULL)
{
iqueue->front=temp;
iqueue->rear=temp;
}
else
{
iqueue->rear->next=temp;
iqueue->rear=temp;
}
}
int search(struct queue* queue1,string val) //returns 1 if val found in queue1 else 0
{
if(queue1->front==NULL)
return 0;
struct node *temp=new node;
temp=queue1->front;
while(temp)
{
if(val.compare(temp->value)==0)
return 1;
temp=temp->next;
}
return 0;
}
int globalcounter=23456;
struct queue *bot(struct queue *crawl,ifstream& infile,string text)
{
struct indexnode *newnode=new indexnode;
//cout<<"\n"<<text<<"\toooooooooooo\n";
newnode->link=text;
newnode->down=new Trie;
newnode->down->abc=globalcounter++;
//cout<<"\n"<<newnode->link<<"\toooooooooooo\n";
newnode->next=NULL;
//indexnode->nop=0;
//Trie *word=new Trie;
if(infile==NULL)
return NULL;
cout<<"BOT_START\n";
string line;
string tri[10000];
//char *v;
string v;
string mxy;
int n=0;
while(getline(infile,line))
{
string link="";
cout<<"\n "<<line<<"\t\n";
int i=0,flag=0,flag1=0,x=0,m=0;
tri[x]="";
for(i=0;i<line.length()-1;i++)
{
if(line[i]==' '||line[i]=='*' && line[i+1]=='*'||line[i]=='*'||line[i]==';'||line[i]=='.'||line[i]=='/')
{
x++;
//tri[x-1][m]='\0';
//v+='\0';
//cout<<"\n***********************************************************"<<v<<endl;
cout<<"\n";
tri[x-1]=v;
newnode->down->addWord(v);
if(newnode->down->searchWord(v))
{
int a;
cout<<"HHHHHHHHHHHHHUUUUUUUUUUUUUUUUUUUUUURRRRRRRRRRRRRRRRRRRRRAAAAAAAAAAAAAYYYYYYYYYYYYYY\n";
cout<<newnode->down->abc<<endl;
//cin>>a;
}
mxy=v;
v="";
m=0;
//tri[x]="";
}
else
{
v+=line[i];
//tri[x][m]=line[i];
cout<<" "<<tri[x][m++]<<" "<<line[i]<<" "<<v;
}
//cout<<"\t.....miiii...miiii....."<<tri[x]<<" ";
if(line[i]=='*' && line[i+1]=='*' && flag==0)
{
flag=1;
i+=2;
}
if(line[i]=='*' && line[i+1]=='*' && flag==1)
{
flag=0;
flag1=1;
i+=2;
}
if(flag==1 && flag1==0)
{
link+=line[i];
}
if(flag1==1)
{
link+='\0';
n++;
cout<<"\nLink:"<<link<<endl;
if(search(crawl,link)==0)
{
cout<<"Link not found in queue\n";
crawl=push(link,crawl);
}
else
cout<<"Link found in queue\n";
link="";
flag1=0;
}
//
//
//
//
}
}
int xt;
//newnode->down=word;
if(!newnode->down)
{
int a;
cout<<"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
//cin>>a;
}
//cout<<"````````````````````````` "<<newnode->down->abc;
//int a;
//cout<<newnode->down;
//cin>>a;
/*if(newnode->down->searchWord(" ")||newnode->down->searchWord("This")||newnode->down->searchWord(mxy))
{
int a;
cout<<"DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD\n";
cin>>a;
cin>>a;
}*/
//cout<<newnode->down->root->getMarker();
//cin>>a;
//cin>>xt;
//displayIndexQueue();
pushindex(newnode);
infile.close();
cout<<"BOT_END\n";
return crawl;
}
struct queue *merge(struct queue *queue1,struct queue *queue2)
{
if(queue1->front==NULL)
return queue2;
else if(queue2->front==NULL)
return queue1;
else
{
struct node *temp=queue2->front;
while(temp)
{
if(search(queue1,temp->value)==0)
queue1=push(temp->value,queue1);
temp=temp->next;
}
/*queue1->rear->next=queue2->front;
queue1->rear=queue1->rear->next;*/
return queue1;
}
}
/*struct queue *checkduplicate(struct queue *queue1,struct queue *queue2)
{
if(queue1->front==NULL || queue2->front==NULL)
return NULL;
struct queue *tempqueue=createqueue();
struct node *temp=queue1->front;
while(temp)
{
if(search(queue2,temp->value)==0)
{
tempqueue=push(temp->value,tempqueue);
}
temp=temp->next;
}
return tempqueue;
}*/
struct queue *spider(struct queue *crawl,ifstream& infile,string text)
{
struct queue *queue1=createqueue();
if(infile==NULL)
return NULL;
queue1=bot(queue1,infile,text);
if(queue1->front==NULL) //check whether there are no links in the queue1
return crawl;
cout<<"SPIDER:Linked list returned by bot:\n";
display(queue1);
cout<<"\n";
cout<<"SPIDER:Displaying crawl before merge:\n\n";
display(crawl);
crawl=merge(crawl,queue1);
//queue1=checkduplicate(queue1,crawl);
cout<<"SPIDER:Displaying crawl after merge:\n\n";
display(crawl);
cout<<"\n";
struct node *temp=queue1->front;
while(temp)
{
ifstream infile1;
char *link=new char[((temp->value).length())+1];
strcpy(link,(temp->value).c_str());
infile1.open(link);
cout<<"Spider is inside : "<<link<<endl;
crawl=spider(crawl,infile1,string(link));
temp=temp->next;
}
return crawl;
}
void displayIndexQueue()
{
if(iqueue->front==NULL)
{
cout<<"iqueue is empty----------------------------------------------\n";
return;
}
struct indexnode *temp=iqueue->front;
while(temp)
{
cout<<temp->link<<endl;
//cout<<"6666666666666666666666666666666666666666666666666666666666666666666666\n";
//if(temp->link=="/home/abhishek/Desktop/eco/testproject2_1_1.txt")
//{
if(temp->down->searchWord("this"))
{
cout<<"this FOUND\n000000000000000000000000000=====================================================================000000000";
}
if(temp->down->searchWord("This"))
{
cout<<"This FOUND\n000000000000000000000000000=====================================================================000000000";
}
if(temp->down->searchWord("movie"))
{
cout<<"MOVIE FOUND\n000000000000000000000000000=====================================================================000000000";
}
cout<<"INSIDE IF OF displayIndexQueue\n";
//cout<<endl<<temp->link<<" &&&&&&&&&&& ";
temp=temp->next;
}
}
struct user
{
string first_name;
string last_name;
int age;
string email;
string password;
};
struct user users[100];
int globalcount;
int validatename(string name)
{
int len=name.length(),flag=0,i=0;
while(flag==0 && i<len)
{
if(!((name[i]>='a' && name[i]<='z') || (name[i]>='A' && name[i]<='Z')))
{
flag=1;
break;
}
i++;
}
if(flag==0)
{
return 1;
}
else
{
return 0;
}
}
int validateemail(string email)
{
if(!((email[0]>='a' && email[0]<='z') || (email[0]>='A' && email[0]<='Z')))
return 0;
int len=email.length();
int a=0,b=0,c=0;
for(int i=0;i<len;i++)
{
if(email[i]=='#')
a=i;
else if(email[i]=='.')
b=i;
}
if(b<a+2)
return 0;
if(b==len-1 ||b==len-2)
return 0;
return 1;
}
int getch() {
struct termios oldt, newt;
int ch;
tcgetattr(STDIN_FILENO, &oldt);
newt = oldt;
newt.c_lflag &= ~(ICANON | ECHO);
tcsetattr(STDIN_FILENO, TCSANOW, &newt);
ch = getchar();
tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
fflush(stdin);
return ch;
}
string inputpassword()
{
char password[100];
for(int i=0;i<100;i++)
{
char ch;
ch=getch();
if(ch=='\n')
break;
password[i]=ch;
cout<<"*";
}
return (string)password;
}
int validatepassword(string password)
{
int a=0,b=0,c=0,d=0;
int len=password.length();
if(len<6)
return 0;
for(int i=0;i<len;i++)
{
if(password[i]>='A' && password[i]<='Z')
a++;
else if(password[i]>='a' && password[i]<='z')
b++;
else if(password[i]>='0' && password[i]<='9')
c++;
else
d++;
}
if(a==0 || b==0 || c==0 || d==0)
return 0;
return 1;
}
string encrypt(string input)
{
int len=input.length();
for(int i=0;i<len;i++)
{
if(i%2==0)
input[i]=input[i]+5;
else
input[i]=input[i]-5;
}
return input;
}
string decrypt(string line)
{
int templ=line.length();
int count_spaces=0,odd=0;
for(int i=0;i<templ;i++)
{
if(line[i]==' ')
{
odd=-1;
count_spaces++;
}
if(count_spaces==2)
{
if(line[i]!=' ')
{
line[i]=line[i];
}
}
else
{
if(line[i]!=' ')
{
if(odd%2==0)
line[i]=line[i]-5;
else
line[i]=line[i]+5;
}
}
odd++;
}
return line;
}
int checkexisting(string email)
{
cout<<"checkexisting called\n";
for(int i=0;i<=globalcount;i++)
{
if(users[i].email.compare(email)==0)
{
cout<<"checkexisting returning 1\n";
return 1;
}
}
cout<<"checkexisting returning 0\n";
return 0;
}
struct user *sign_up()
{
string first_name1,last_name1,email1,password1,password2;
int age1;
char test;
cout<<"\nHere are a few syntax rules for signing up on Black Box:\n";
cout<<"1.Age must not be less than 12 years.\n";
cout<<"2.First name and Last name fields will accept only alphabets.\n";
cout<<"3.email address must be of the form 'user#example.com'.\n";
cout<<"4.Password must be at least 6 characters in length and must include at least one upper case";
cout<<" alphabet,one lower case alphabet,one numeral and one special character.\n\n\n";
cout<<"First Name: ";
getline(cin,first_name1);
while(validatename(first_name1)==0)
{
cout<<"Invalid first name entered.\n";
cout<<"\nFirst name can have only alphabets(no spaces,no special characters and no numerals.\n";
cout<<"Enter your first name again: ";
getline(cin,first_name1);
}
cout<<"\nLast Name: ";
getline(cin,last_name1);
while(validatename(last_name1)==0)
{
cout<<"Invalid last name entered.\n";
cout<<"\nLast name can have only alphabets(no spaces,no special characters and no numerals.\n";
cout<<"Enter your last name again: ";
getline(cin,last_name1);
}
cout<<"\nAge: ";
cin>>age1;
if(age1<12)
{
cout<<"Sorry, but according to our TERMS OF USE, no user of age less than 12 can be allowed ";
cout<<"to create an account on Black Box.\n";
return NULL;
}
fflush(stdin);
cin.ignore();
cout<<"\nEmail address : ";
getline(cin,email1);
while(validateemail(email1)==0 || checkexisting(email1)==1)
{
if(validateemail(email1)==0)
{
cout<<"\nInvalid email entered.\n";
cout<<"Email address can only be of the form abc#xyz.pqr.\n";
cout<<"Enter the email address again: ";
}
if(checkexisting(email1)==1)
{
cout<<"\nEmail id already registered.\nChoose a new one.\n";
}
cout<<"\nEnter Email address again: ";
getline(cin,email1);
}
cout<<"\nChoose a password: ";
password1=inputpassword();
cout<<"\nRetype Password: ";
password2=inputpassword();
while(validatepassword(password1)==0 || password1.compare(password2)!=0)
{
if(validatepassword(password1)==0)
{
cout<<"Invalid password enterd.\n";
cout<<"Password must be at least 6 characters in length and must include at least";
cout<<" one upper case alphabet,one lower case alphabet,one numeral and one special character.\n";
}
if(password1.compare(password2)!=0)
{
cout<<"\nPasswords do not match.\n";
}
cout<<"Enter the password again: ";
password1=inputpassword();
cout<<"\nRetype Password: ";
password2=inputpassword();
}
struct user *newuser=new user;
newuser->first_name=first_name1;
newuser->last_name=last_name1;
newuser->age=age1;
newuser->email=email1;
newuser->password=password1;
ofstream outfile("userfile.txt",ios::app);
if(outfile)
{
outfile<<encrypt(newuser->first_name)<<" "<<encrypt(newuser->last_name)<<" "<<newuser->age<<" "<<encrypt(newuser->email)<<" "<<encrypt(newuser->password)<<endl;
}
outfile.close();
return newuser;
}
struct user extract(string line)
{
int len=line.length();
int spaces=0;
string first="",last="",age="",email="",password="";
for(int i=0;i<len;i++)
{
if(line[i]==' ')
spaces++;
else
{
if(spaces==0)
first+=line[i];
else if(spaces==1)
last+=line[i];
else if(spaces==2)
age+=line[i];
else if(spaces==3)
email+=line[i];
else
password+=line[i];
}
}
struct user newuser;
newuser.first_name=first;
newuser.last_name=last;
stringstream convert(age);
newuser.age=0;
convert>>newuser.age;
newuser.email=email;
newuser.password=password;
return newuser;
}
int loadusers()
{
string line;
ifstream infile;
infile.open("userfile.txt");
if(!infile)
return 0;
while(getline(infile,line))
{
globalcount++;
line=decrypt(line);
users[globalcount]=extract(line);
}
}
int login()
{
string email,password;
char choice='y';
while(choice=='y'||choice=='Y')
{
cout<<"\nEnter email address: ";
cin>>email;
cout<<"\nEnter password: ";
cin>>password;
int flag1=0,cur=-1;
for(int i=0;i<=globalcount;i++)
{
if(email.compare(users[i].email)==0 && password.compare(users[i].password)==0)
{
cur=i;
flag1=1;
break;
}
}
if(flag1==1)
{
cout<<"Welcome "<<users[cur].first_name<<endl;
break;
}
else
{
cout<<"Wanna try again?(y/n): ";
cin>>choice;
}
}
if(choice=='y'|| choice=='Y')
return 1;
else
return 0;
}
int account_info()
{
int choice=0,m=1;
cout<<"1.Sign up\n2.Log in\n3.Continue without an account\n4.Exit from Black Box.\nEnter your choice: ";
cin>>choice;
fflush(stdin);
cin.ignore();
struct user *new_user=NULL;
switch(choice)
{
case 1:
new_user=new user;
new_user=sign_up();
if(new_user==NULL)
{
cout<<"Sign up failed.";
choice=3;
}
else
{
cout<<"Successful Sign up.\n";
ofstream outfile;
string newusernamefile="/home/aakash/project/users/"+encrypt(new_user->email)+".txt";
//char *newusernamefile1=newusernamefile.c_str();
outfile.open(newusernamefile.c_str());
outfile<<new_user->first_name;
outfile.close();
break;
}
case 2:
if(login()==1)
{
cout<<"Successful login.\n";
break;
}
else
{
cout<<"Login failed.\n";
choice=3;
}
case 3:
cout<<"Welcome to Black Box3.\n";
break;
case 4:
exit(0);
break;
default:
cout<<"Wrong choice.\n";
};
if(new_user)
{
cout<<"\nThe details entered are:\n";
cout<<new_user->first_name<<endl;
cout<<new_user->last_name<<endl;
cout<<new_user->age<<endl;
cout<<new_user->email<<endl;
cout<<new_user->password;
}
cout<<endl<<endl;
return 1;
}
void displayusers()
{
for(int i=0;i<=globalcount;i++)
{
cout<<"\n"<<users[i].first_name<<" "<<users[i].last_name<<" "<<users[i].age<<" "<<users[i].email<<" "<<users[i].password;
}
cout<<endl;
}
int main()
{
globalcount=-1;
int temp1=loadusers();
if(globalcount!=-1)
displayusers();
int temp=account_info();
int a;
//cin>>a;
struct queue *crawl=createqueue();
iqueue=new indexqueue;
iqueue->front=NULL;
iqueue->rear=NULL;
string text;
text="inputproject.txt";
ifstream infile;
infile.open("inputproject.txt");
if(!infile)
{
cout<<"inputproject.txt not open\n";
return 0;
}
else
cout<<"inputproject.txt successfully opened\n";
crawl=spider(crawl,infile,text);
cout<<"Hey\n";
if(crawl->front==NULL)
return 1;
cout<<"main:Displaying crawl\n";
Trie *dummy=new Trie;
dummy->addWord("movie");
dummy->addWord("harry potter");
dummy->addWord("rajnikanth");
if(dummy->searchWord("movie"))
{
cout<<"MOVIE FOUND IN DUMMY^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n\n";
}
if(dummy->searchWord("harry potter"))
{
cout<<"harry potter FOUND IN DUMMY^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n\n";
}
if(dummy->searchWord("rajnikanth"))
{
cout<<"rajnikanth FOUND IN DUMMY^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n\n";
}
cout<<iqueue->front->down;
display(crawl);
displayIndexQueue();
string searchstring;
cout<<"\n Enter the string you want to enter\t";
getline(cin,searchstring);
string arraystring[20];int m=0,n=0;
for(int i=0;i<20;i++)
arraystring[i]="";
for(int i=0;i<searchstring.length();i++)
{
cout<<"\n segregating string\t";
if(searchstring[i]==' ')
{
m=m+1;
arraystring[m]="";
cout<<"AAAAAAAAAAA\n";
}
else
{
arraystring[m]+=searchstring[i];
cout<<"BBBBBBBBBBBB\n";
}
/*if((searchstring[i]>='a'&&searchstring[i]<='z')||(searchstring[i]>='A'&&searchstring[i]<='Z')||searchstring[i]=='/'||searchstring[i]=='_')
{
arraystring[m]+=searchstring[i] ;
cout<<"\n adding to array\t";
}
else
{
m++;
//n=0;
cout<<"\n incrementing 1\t";
}*/
}
//Searching for individual string to be as a part of links we crawled "State Automata Search"
cout<<"\n"<<iqueue->front->link<<"\n-------------------\t";
indexqueue iqu[m];
struct indexnode *tempiq;
for(int x=0;x<m;x++)
{
cout<<"\n 11111111111111\t";
//iqu[x]=new createindexqueue();
//=createindexnode(" ");
tempiq=iqueue->front; //above mentioned code segment
cout<<"\n"<<iqueue->front->link<<""<<iqueue->front<<"\t________________________";
if(tempiq)// && iqueue->front)
cout<<"\n aaaaaaaaaaaaaaaaaaaa\t";
while(tempiq)
{
cout<<"\n entered the tempiq inorder to search\t";
indexnode *temp;
temp=(iqu[x].front);
char *c,*c2;
strcpy(c,(tempiq->link).c_str());
strcpy(c2,arraystring[x].c_str());
if(searchauto(c2,c))
{
cout<<"\n checking for automata\t";
while(temp)
{
cout<<"\n entered while\t";
if(temp->next!=NULL)
temp=temp->next;
else
{
cout<<"\n creaing indexes\t";
indexnode *am=createindexnode(tempiq->link);
temp->next=am;
}
}
}
tempiq=tempiq->next;
}
}
for(int i=0;i<m;i++)
{
indexqueue q=iqu[i];
indexnode *qt=q.front;
while(qt)
{
cout<<"---"<<qt->link<<"---";
qt=qt->next;
cout<<"\n";
}
cout<<"\n\n\n";
}
//cout<<endl<<iqueue->front->down->abc<<endl;
//cout<<iqueue->rear->down->abc;
cout<<endl;
return 1;
}
I'm not sure that it's the problem that cause your segmentation fault but... it's a problem.
With the following instructions
char *c,*c2;
strcpy(c,(tempiq->link).c_str());
strcpy(c2,arraystring[x].c_str());
if(searchauto(c2,c))
you write, with strcpy(), in a couple undefined (c and c2 are uninitialized) and unallocated memory areas.
Are you sure that you need to copy this couple of std::string in char * pointed area?
In this case, you should allocate the needed memory; something like this
char *c,*c2;
c = new char[(tempiq->link).size()+1U];
c2 = new char[arraystring[x].size()+1U];
strcpy(c,(tempiq->link).c_str());
strcpy(c2,arraystring[x].c_str());
if(searchauto(c2,c))
But remember to delete [] c and c2.
This if you really need a couple of allocated char *.
But I suppose you can simply pass the c_str() value of this couple of std::string to searchauto()
if(searchauto((tempiq->link).c_str(), arraystring[x].c_str()))
if you define const the parameters of searchauto()
int searchauto(const char *pat, const char *txt)
and the first one of computeTransFun()
void computeTransFun(const char *pat, int M, int TF[][NO_OF_CHARS])
p.s.: sorry for my bad English.
stuType Class:
#include<iostream>
#include<cstring>
using namespace std;
#ifndef STUTYPE
#define STUTYPE
class stuType {
private:
string fname;
string lname;
string social;
float gpa;
public:
stuType(void) {
fname = "no_fname";
lname = "no_lname";
social = "no_social";
gpa = 0.0;
}
stuType(string fname_in, string lname_in, string social_in, float gpa_in) {
fname = fname_in;
lname = lname_in;
social = social_in;
gpa = gpa_in;
}
~stuType() {
//Nothing needs to be added here.
}
void set_fname(string new_fname) {
fname = new_fname;
}
void set_lname(string new_lname) {
lname = new_lname;
}
void set_ssn(string new_ssn) {
social = new_ssn;
}
void set_gpa(float new_gpa) {
gpa = new_gpa;
}
string get_fname(void) {
return fname;
}
string get_lname(void) {
return lname;
}
string get_ssn(void) {
return social;
}
float get_gpa(void) {
return gpa;
}
friend istream & operator>>(istream &in, stuType &stu) {
in>>stu.fname;
in>>stu.lname;
in>>stu.social;
in>>stu.gpa;
return in;
}
};
#endif
Sort.cpp:
#include<iostream>
#include<fstream>
#include<cstdlib>
#include<cstring>
#include"stuType.h"
using namespace std;
/*Loads the elements of the object instance with data from the input file.*/
void load(istream &input, stuType Student[], int *size);
/*Used in combination with the shellSort method to exchange the values of two variables in the class object.*/
void exchange(stuType &a, stuType &b);
/*Sorts the objects in ascending order by comparing the values of the lname strings between object indices.*/
void shellSort(stuType Student[], int size);
int main() {
stuType Student[10];
int size;
char inputFile[200];
char outputFile[200];
ifstream input;
ofstream output;
cout<<"[INPUT_FILE]: ";
cin>>inputFile;
cout<<"[OUTPUT_FILE]: ";
cin>>outputFile;
input.open(inputFile);
output.open(outputFile);
if (input.fail()) {
cerr<<"\n[FILE] Error opening '"<<inputFile<<"'"<<endl;
exit(1);
}
if (output.fail()) {
cerr<<"\n[FILE] Error opening '"<<outputFile<<"'"<<endl;
exit(1);
}
load(input, Student, &size);
shellSort(Student, size);
return 0;
}
void load(istream &input, stuType Student[], int *size) {
int length = 0, i = 0;
float gpa;
string social;
string fname;
string lname;
while(input >> social >> fname >> lname >> gpa) {
cout<<"[Node::Load] Setting 'social' for index ["<<i<<"] to "<<social<<endl;
Student[i].set_ssn(social);
cout<<"[Node::Load] Setting 'fname' for index ["<<i<<"] to "<<fname<<endl;
Student[i].set_fname(fname);
cout<<"[Node::Load] Setting 'lname' for index ["<<i<<"] to "<<lname<<endl;
Student[i].set_lname(lname);
cout<<"[Node::Load] Setting 'gpa' for index ["<<i<<"] to "<<gpa<<endl;
Student[i].set_gpa(gpa);
cout<<"[Node::Load] Incrementing 'length'..."<<endl;
length++;
cout<<"[Node::Load] Incrementing 'i'..."<<endl;
i++;
}
cout<<"==================================="<<endl;
for (int i = 0; i<length; i++) {
cout<<"[ENTRY] Index: "<<i<<" | SSN: "<<Student[i].get_ssn()<<" | fname: "<<Student[i].get_fname()<<" | lname: "<<Student[i].get_lname()<<" | gpa: "<<Student[i].get_gpa()<<endl;
}
cout<<"==================================="<<endl;
*size = length;
}
void exchange(stuType &a, stuType &b) {
stuType *temp;
*temp = a;
a = b;
b = *temp;
delete temp;
}
void shellSort(stuType Student[], int size) {
int gap = size/2;
bool passOK;
while(gap>0) {
passOK = true;
for(int i = 0; i<size-gap; i++) {
if (strcmp(Student[i].get_lname(), Student[i+gap].get_lname)>0) {
cout<<"[Node::Sort] Exchanging Index ["<<i<<"] with Index ["<<i+gap<<"]..."<<endl;
exchange(Student[i], Student[i+gap]);
passOK = false;
} else if (strcmp(Student[i].get_lname(), Student[i+gap].get_lname())==0) {
if (strcmp(Student[i].get_fname(), Student[i+gap].get_fname())>0) {
cout<<"[Node::Sort] Exchanging Index ["<<i<<"] with Index ["<<i+gap<<"]..."<<endl;
exchange(Student[i], Student[i+gap]);
passOK = false;
}
}
}
if (passOK) {
gap /= 2;
}
}
}
strcmp() expects to receive a character array to do the comparison, but since I am using strings, I cannot do that. What is an alternative? The variable 'lname' needs to be compared and should return true if Student[i].get_lname() is greater than Student[i+gap].get_lname(). The exchange function will then be called and exchange the values of the object's local variables. The objects should be sorted in ascending order based on the value of the 'lname' variable and the 'fname' variable should only be referenced if the two 'lname's being compared are the same.
C++ strings provide implementations of operators < and >, so you can use them instead of strcmp:
std::string a = "hello";
std::string b = "world";
if (a < b) {
cout << a << " is less than " << b << endl;
}
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.
Hes my code and I can't figure out where I'm getting the divide by zero problem.
mreviewApp.cpp
const int SIZE = 80;
const char DELIMIT = '|';
void parseLine(const char line[], string& title, int& rating);
void stringTrim(char st[]);
void printMrList(std::vector <Mreview> mrList);
Mreview searchTitle(std::vector <Mreview> &mrList, string title);
int main()
{
ifstream fin;
fin.open("rating_list.txt");
if (fin.fail()) {
cerr << "Input file opening error.\n";
exit(1);
}
char line[SIZE];
string title;
int rating;
int lineCount = 0;
std::vector <Mreview> mrList;
/* Process one line at a time */
// Read the first line
fin.getline(line, SIZE);
stringTrim(line);
// Process loop
while (strlen(line) != 0) {
parseLine(line, title, rating);
lineCount++;
Mreview review = searchTitle(mrList, title);
review.addScore(rating);
// Read the next line
fin.getline(line, SIZE);
stringTrim(line);
}
cout << "** PROCESS DONE. There were " << mrList.size() << " movie titles. **\n\n";
printMrList(mrList);
// Close the input file before exit.
fin.close();
system("Pause");
return 0;
}
void parseLine(const char line[], string& title, int& rating)
{
char s[SIZE], r[SIZE];
const char *ptr, *temp1;
char *temp2;
ptr = strchr(line, DELIMIT);
if (ptr != NULL) {
// First grab the title string (until '|').
temp1 = line;
temp2 = s;
while (temp1 != ptr)
*temp2++ = *temp1++;
*temp2 = '\0';
stringTrim(s);
title = s;
// Second grab the rating number
temp1 = ptr+1;
temp2 = r;
while (*temp1 != '\0')
*temp2++ = *temp1++;
*temp2 = '\0';
stringTrim(r);
rating = atoi(r);
}
else {
title = "";
rating = 0;
}
}
void stringTrim(char st[])
{
char* ptr;
for (ptr = st; *ptr; ptr++) ;
for (ptr--; *ptr == ' ' && ptr >= st; ptr--) ;
ptr++;
*ptr = '\0';
for (ptr = st; *ptr && *ptr == ' '; ptr++) ;
if (*ptr && ptr != st) {
char* ptr2;
for (ptr2 = st; *ptr; *ptr2++ = *ptr++) ;
*ptr2 = '\0';
}
}
void printMrList(std::vector <Mreview> mrList)
{
std::vector<Mreview>::iterator itr;
for(itr = mrList.begin(); itr != mrList.end(); itr++) {
Mreview review = *(itr);
cout << review.getTitle() << "\t\t" << review.getTotalScore() << "\t\t" << review.aveRating() << endl;
}
}
Mreview searchTitle(std::vector <Mreview> &mrList, string title)
{
Mreview review (title);
std::vector<Mreview>::iterator itr;
for(itr = mrList.begin(); itr != mrList.end(); itr++) {
Mreview r2d2 = *(itr);
if(review.getTitle() == r2d2.getTitle())
return r2d2;
}
mrList.push_back(review);
return review;
}
mreview.cpp
Mreview::Mreview(string ttl)
: title(ttl), totalScore(0), numRatings(0) {}
Mreview::Mreview(string ttl, int score)
: title(ttl), totalScore(score), numRatings(1) {}
void Mreview::addScore(int score)
{
this->totalScore += score;
this->numRatings += 1;
}
double Mreview::aveRating() const
{
double rating = totalScore/numRatings;
return rating;
}
mreview.h
#ifndef MREVIEW_H
#define MREVIEW_H
#include <string>
using namespace std;
class Mreview
{
public:
Mreview(string ttl = "N/A");
Mreview(string ttl, int firstScore);
string getTitle() const { return title; }
int getTotalScore() const { return totalScore; }
int getNumRatings() const { return numRatings; }
void addScore(int score);
double aveRating() const;
private:
string title;
int totalScore;
int numRatings;
};
#endif
My problem is that I am unable to figure out what I have to do to fix the problem. I have read the comments and I am still confused.
You're allocating (and copying!) a vector of Mreview objects, all of which are being constructed with the default ctor, so numRatings defaults to 0, and you are doing nothing to ensure that aveRating() is never called on unmodified objects or at the very least protects itself from numRatings being 0.
Edit: Easiest fix:
double Mreview::aveRating() const {
if (numRatings == 0)
return 0.;
else
return static_cast<double>(totalScore)/numRatings;
}
A further fix, IMO, would be to store Mreview pointers (ideally shared_ptr) in the vector and newing them when the first score is to be added rather than earlier.
Not the divide by zero error, but...
double Mreview::aveRating() const
{
double rating = totalScore/numRatings;
return rating;
}
You are taking two integer values and storing it in a double without typecasting... you have to cast either totalScore or numRatings to a double like:
double Mreview::aveRating() const
{
double rating = (double)totalScore/numRatings;
return rating;
}
When looking for divide by zero problems, look for / and % operators. I see only one / in your code.
I only see one actual division operation...
double Mreview::aveRating() const {
double rating = totalScore/numRatings;
return rating;
}
...so is it there?
Can you run it in a debugger and let it tell you where the trap occurred?
It looks like if the length of the line is 0 after trimming, then printMrList() can be called without review.addScore() being called first. In that case, printMrList() calls review.aveRating() which tries to divide totalScore by numRatings. Both of these values are 0, so a divide by zero error occurs.