I'm not sure how to do the followings...
modify insertion() function, so that the new person will be inserted into the directory at the sorted place by the person’s name.
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#pragma warning(disable: 4996)
#define max 100
typedef enum { diploma, bachelor, master, doctor } education;
const char* getDegreeName(enum education degree){
switch (degree){
case diploma: return "diploma";
break;
case bachelor: return "bachelor";
break;
case master: return "master";
break;
case doctor: return"doctor";
break;
}
}
struct person { // a node to hold personal details
char name[30];
char email[30];
int phone;
education degree;
};
struct person directory[max]; // an array of structures, 100 entries
int tail = 0; // global variable
int i = 0;
int z = 0;
char temp[30];
void flush(); // forward declaration of functions
void branching(char c);
int insertion();
int print_person(int i);
int print_all();
int search_person();
int delete_person();
int main() { // print a menu for selection
char ch = 'i';
ungetc('\n', stdin); // inject the newline character into input buffer
do {
printf("Enter your selection\n");
printf("\ti: insert a new entry\n");
printf("\td: delete an entry\n");
printf("\ts: search an entry\n");
printf("\tp: print all entries\n");
printf("\tq: quit \n");
flush(); // flush the input buffer. To be discussed later
ch = tolower(getchar());
branching(ch);
} while (ch != 113);
return 0;
}
void flush() { // flush the input buffer. To be discussed later
int c;
do {
c = getchar();
} while (c != '\n' && c != EOF);
}
void branching(char c) { // branch to different tasks
switch (c) {
case 'i':
insertion();
break;
case 's':
search_person();
break;
case 'd':
delete_person();
break;
case 'p':
print_all();
break;
case 'q':
break;
default:
printf("Invalid input\n");
}
}
int insertion() { // insert a new entry at the end
if (tail == max) {
printf("There are no more places to insert.\n");
return -1;
}
else {
printf("Enter name, phone, email:\n");
printf("Enter 0 for diploma, 1 for bachlor, 2 for master and 3 for doctor\n");
scanf("%s", directory[tail].name);
scanf("%d", &directory[tail].phone, sizeof(directory[tail].phone));
scanf("%s", directory[tail].email);
scanf("%d", &directory[tail].degree); //sacaning the degree
tail++;
printf("The number of entries = %d\n", tail);
return 0;
}
}
int print_person(int i) {
// print all information one person in the directory
printf("\n\nname = %s\n", directory[i].name);
printf("email = %s\n", directory[i].email);
printf("phone = %d\n", directory[i].phone);
printf("degree = %s\n", getDegreeName(directory[i].degree));
return 0;
}
int print_all() {
// print all information each person in the contactbook
int i;
if (tail == 0) {
printf("No entries found.");
}
else {
for (i = 0; i < tail; i++) {
print_person(i);
}
}
return 0;
}
int search_person() { // print phone and email via name
char sname[30]; int i;
printf("Please enter the name to be searched for:\n");
scanf("%s", sname); //sname is an array, no & needed
for (i = 0; i<tail; i++)
if (strcmp(sname, directory[i].name) == 0) {
print_person(i);
return i;
}
printf("The name does not exist.\n");
return -1;
}
int delete_person() {
int i, k;
k = search_person();
if (k == -1) {
printf("The name does not exist.\n"); return -1;
}
else {
for (i = k; i<tail; i++) {
strcpy(directory[i].name, directory[i + 1].name);
directory[i].phone = directory[i + 1].phone;
strcpy(directory[i].email, directory[i + 1].email);
printf("The index deleted is: %d\n", k);
}
tail--;
return k;
}
}
int insertion()
{
if (tail == max)
{
printf("There are no more places to insert.\n");
return -1;
}
return doInsertion();
}
int doInsertion() {
bool done = false;
char name[30];
char email[30];
double phone = 0;
double degree = 0;
int i = 0;
struct person toadd;
struct person tmpdirectory[tail+1];
// Ask user for input
printf("Enter name, phone, email:\n");
printf("Enter 0 for diploma, 1 for bachlor, 2 for master and 3 for doctor\n");
// Get user input
scanf("%s", name, sizeof(name));
scanf("%d", phone);
scanf("%s", sizeof(email));
scanf("%d", degree);
toadd.name = name;
toadd.phone = phone;
toadd.email = email;
toadd.degree = degree;
// Loop for over the length of the current array
for(; i < tail ; ++i)
{
// Check if the new item is alphabetically before the next item
if(strcmp(name, directory[i].name) < 0)
{
// Insert the new item and break the loop
tmpdirectory[i] = toadd;
done = true;
break;
}
// Copy over a item and keep looking for the insert spot
tmpdirectory[i] = directory[i];
}
// If we haven’t inserted yet its the last item in the list
if(done == false)
{
tmpdirectory[i] = toadd;
}
// otherwise we need to copy over the remaining items in the list
else
{
for(; i < tail ; ++i)
{
tmpdirectory[i+1]; = directory[i];
}
}
// increase list count
++tail;
// copy the struct
struct person dictionary[tail];
directory = tmpdirectory;
printf("The number of entries = %d\n", tail);
return 0;
}
Related
I am trying to make program that get infix to postfix but when I entered +- in the infix equation
the output should be +- but I find that the output is ++ and if infix is -+ the output is --
it have been a week since I started to solve that problem
#include <iostream>
#include <string>
using namespace std;
//classes
class arr
{
private:
char *items;
int size;
int length;
public:
//default constructor
arr()
{
items = new char[100];
size = 100;
length = 0;
}
//constructor with parameters
arr(int arraySize)
{
items = new char[arraySize];
size = arraySize;
length = 0;
}
//check if array is empty
bool is_empty()
{
return length == 0 ? true : false;
}
//check if array full
bool is_full()
{
return length >= size - 1 ? true : false;
}
//returns array length
int getLength()
{
return length;
}
//return array size
int getSize()
{
return size;
}
//get array address
char *getAddress()
{
return &items[0];
}
//fill number of items in array based on elementNum
void fill(int elementNum)
{
char ch;
cout << "Enter characters you want to add\n";
if (elementNum > size - 1)
{
cout << "can't use elements number largger than " << size - 1;
return;
}
for (int i = 0; i < elementNum; i++)
{
cin >> ch;
insert(i, ch);
}
}
//display all elements in the array
void display()
{
if (is_empty())
{
cout << "there are no data /n";
return;
}
cout << "Array items are :\n";
for (int i = 0; i < length; i++)
{
cout << items[i] << "\t";
}
cout << endl;
}
void append(char ch)
{
insert(length, ch);
}
void insert(int index, char newItem)
{
if (is_full() || length<index || length + 1 == size)
{
cout << "\nSorry array is full\ncan't append letter more\n";
return;
}
else {
for (int i = length; i >= index; i--)
{
items[i + 1] = items[i];
}
items[index] = newItem;
length++;
}
}
int search(char ch)
{
if (!is_empty())
for (int i = 1; i <= length; i++)
{
if (items[i] == ch)
return i;
}
return 0;
}
void del(int index)
{
if (is_empty() || length<index) {
cout << "sorry can't delete item which is doesn't exist";
return;
}
for (int i = index; i < length; i++)
{
items[i] = items[i + 1];
}
length--;
}
void changeSize(int newSize)
{
if (newSize <= length - 1)
{
cout << "can't change size because the new size is small";
return;
}
char *tempItems = new char[newSize];
size = newSize;
for (int i = 0; i < length; i++)
{
tempItems[i] = items[i];
}
items = tempItems;
tempItems = NULL;
}
//merge two arrays
void merge(arr a)
{
this->size = this->size + a.getSize();
for (int i = 0; i < a.getLength(); i++)
{
items[i + length] = a.getAddress()[i];
}
length = this->length + a.getLength();
}
};
class stackUsingArray {
private:
int top;
arr a;
public:
stackUsingArray()
{
top = -1;
}
stackUsingArray(int stackSize)
{
a.changeSize(stackSize);
top = -1;
}
bool is_empty()
{
return(top == -1);
}
bool is_full()
{
return(a.is_full());
}
void push(char ch)
{
top++;
a.append(ch);
}
char pop()
{
if (is_empty())
{
cout << "sorry the stack is empty";
}
else
return a.getAddress()[top--];
}
int peekTop() {
return top;
}
void display()
{
//first way of display
for (int i = top; i >= 0; i--)
{
cout << a.getAddress()[i];
}
//second way of display
//stackUsingArray c;
//char ch;
//for (int i = top; i >= 0; i--)
// c.push(this->pop());
//for (int i = c.peekTop(); i >= 0; i--)
//{
// ch=c.pop();
// this->push(ch);
// cout << ch;
//}
}
int search(char ch)
{
for (int i = top; i >= 0; i--)
{
if (a.getAddress()[i] == ch)
return i;
}
return -1;
}
char topDisplay()
{
return a.getAddress()[top];
}
};
class stackUsingLinkedList {};
//functions
string infixToPostfix(string infix);
short prec(char ch);
int main()
{
//infix and postfix
stackUsingArray c;
cout<<infixToPostfix("x+y-z");
system("pause");
return 0;
}
string infixToPostfix(string infix)
{
string postfix = "";
stackUsingArray sta;
char ch;
char test;
for (int i = 0; i < infix.length(); i++)
{
switch (prec(infix[i]))
{
case 0:
postfix.append(1, infix[i]);
break;
case 1:
sta.push(infix[i]);
break;
//case 2:
// ch = sta.pop();
// while (ch != '(')
// {
// postfix.append(1, ch);
// ch = sta.pop();
// }
// break;
case 3:
// if (sta.is_empty())
// {
// goto k270;
// }
// ch = sta.pop();
// while (prec(ch) > 3)
// {
// postfix.append(1, ch);
// if (sta.is_empty()) {
// //sta.push(infix[i]);
// goto k270;
// }
// ch = sta.pop();
// }
// sta.push(ch);
//k270:
// sta.push(infix[i]);
test = sta.topDisplay();
if (sta.is_empty())
{
sta.push(infix[i]);
test = sta.topDisplay();
}
else
{
ch = sta.pop();
test = sta.topDisplay();
if (prec(ch) >= 3)
{
postfix += ch;
}
sta.push(infix[i]);
}
}
}
while (!sta.is_empty())
{
postfix.append(1, sta.pop());
}
return postfix;
}
short prec(char ch)
{
if (ch == '(')
return 1;
if (ch == ')')
return 2;
if (ch == '+')
return 3;
if (ch == '-')
return 3;
if (ch == '*')
return 4;
if (ch == '/')
return 4;
return 0;
}
thanks to #IgorTandetnik I figured out that I should del last item from the array when I pop from stack
In the program I need a structure with a stack, and list. Opportunities to add a product, display a list of products, delete the last product.
I wrote this program, but I get a huge amount of errors.
Can you tell me what is wrong with my program?
#include<stdio.h>
struct Stack
{
int* stack;
int size = 0;
int Capasity = 0;
Stack() {}
Stack(int aCapasity)
{
stack = new int[aCapasity];
Capasity = aCapasity;
}
~Stack()
{
delete stack;
}
bool push(int var)
{
if (size < Capasity)
{
stack[size] = var;
size++;
return true;
}
else
{
printf("Error, Size == Capasity, use Stack(N) to resize stack");
return false;
}
}
int pop()
{
if (size > 0)
{
size--;
return stack[size];
}
else
{
printf("Error, No elements");
return -1;
}
}
int peek()
{
if (size > 0)
return stack[size - 1];
else
{
printf("Error, No elements");
return -1;
}
}
void showStack()
{
int size_temp = size;
for (; size > 0; size--)
{
printf("%d ", stack[size - 1]);
}
printf("\n");
size = size_temp;
}
};
struct Node
{
char* name = new char[6];
float sumary;
int amount;
Node(char* name, float sumary, int amount) :name(name), sumary(sumary), amount(amount)
{
}
Node() {}
};
int main()
{
int command;
stack<Node> node;
for (;;)
{
printf("Input command:\n 1 - add,\n 2 - delete last,\n 3 - show all,\n 4 - exit\n");
scanf("%d", &command);
switch (command)
{
case 1:
char name[6];
float sumary;
int amount;
printf("Enter name: ");
scanf("%s", &name);
printf("Enter sumary: ");
scanf("%f", &sumary);
printf("Enter amount: ");
scanf("%d", &amount);
node.push(Node(name, sumary, amount));
break;
case 2:
node.pop();
printf("The last have been deleted");
break;
case 3:
while (!example.empty())
{
Node temp = example.top();
example.pop();
cout << temp.name << " " << temp.sumary << " " << temp.amount << endl;
}
break;
case 4:
return 0;
default:
printf("Wrong command...");
break;
}
}
}
I can’t even show errors here, there are too many of them.
I modified you code and now it has no error during the compiling. I don't exactly understand what you want to do with this code. I used STL stack, and the class was useless.
This is the code:
#include <iostream>
#include <stdio.h>
#include <stack>
using namespace std;
struct Node
{
char* name = new char[6];
float sumary;
int amount;
Node(char* name, float sumary, int amount) :name(name), sumary(sumary), amount(amount)
{
}
Node() {}
};
int main()
{
int command;
stack<Node> node;
for (;;)
{
printf("Input command:\n 1 - add,\n 2 - delete last,\n 3 - show all,\n 4 - exit\n");
scanf("%d", &command);
switch (command)
{
case 1:
char name[6];
float sumary;
int amount;
printf("Enter name: ");
scanf("%s", &name);
printf("Enter sumary: ");
scanf("%f", &sumary);
printf("Enter amount: ");
scanf("%d", &amount);
node.push(Node(name, sumary, amount));
break;
case 2:
node.pop();
printf("The last have been deleted");
break;
case 3:
while (!node.empty())
{
Node temp = node.top();
node.pop();
cout << temp.name << " " << temp.sumary << " " << temp.amount << endl;
}
break;
case 4:
return 0;
default:
printf("Wrong command...");
break;
}
}
}
I made a program which adds nodes and edges between those nodes.Now i want to find which node has the maximum count of edges connected to it.Here is my code:
const int N = 15;
struct graf {
int key;
graf *next;
};
void init(graf *gr[]) {
for (int i = 0; i<N; i++) {
gr[i] = NULL;
}
}
int search_node(graf *gr[], int c) {
int flag = 0;
for (int i = 0; i<N; i++) {
if (gr[i]) {
if (gr[i]->key == c)flag = 1;
}
}
return flag;
}
int search_arc(graf *gr[], int c1, int c2) {
int flag = 0;
if (search_node(gr, c1) && search_node(gr, c2)) {
int i = 0;
while (gr[i]->key != c1)
i++;
graf *p = gr[i];
while (p->key != c2 && p->next != NULL)
p = p->next;
if (p->key == c2)
flag = 1;
}
return flag;
}
void add_node(graf *gr[], int c) {
if (search_node(gr, c))
printf("Edge existing !\n");
else {
int j = 0;
while (gr[j] && (j<N))j++;
if (gr[j] == NULL) {
gr[j] = new graf;
gr[j]->key = c;
gr[j]->next = NULL;
}
else
printf("Overflow !\n");
}
}
void add_arc(graf *gr[], int c1, int c2) {
int i = 0;
graf *p;
if (search_arc(gr, c1, c2))
printf("there is edge from node %s to node %s", c1, c2);
else {
if (!(search_node(gr, c1)))
add_node(gr, c1);
if (!(search_node(gr, c2)))
add_node(gr, c2);
while (gr[i]->key != c1)
i++;
p = new graf;
p->key = c2;
p->next = gr[i]->next;
gr[i]->next = p;
}
}
int get_graph_rank(graf*& gr,int i=0)
{
int max = NULL;
if (gr != NULL)
{
//i think to use recursion but i don't know how to start ...
}
return max;
}
int main() {
int c, k;
int menu = NULL, br = NULL;
graf *gr1[N];
init(gr1);
do
{
printf("1. add node\n");
printf("2. add edge\n");
printf("3.get the rang\n");
printf("0. exit\n");
do {
scanf_s("%d",&menu);
} while (menu<0 || menu>4);
switch (menu) {
case 1:
printf("enter edge: ");
scanf_s("%d", &c);
add_node(gr1, c);
break;
case 2:
printf("begining edge: ");
scanf_s("%d", &c);
printf("ending edge: ");
scanf_s("%d", &k);
add_arc(gr1, c, k);
break;
case 3:
get_graph_rank(*gr1);
break;
}
} while (menu != 0);
delete gr1;
}
I hope you could help me write the logic of the function which will return the value of the node ,which has the maximum edges connected to it , and if there is more than one node with the same count of edges connected , return NULL.Thanks in advice .....
Looks like the code uses a singly-linked list node for representing graph nodes. That means your nodes cannot have more than 1 (outgoing) edge. Not sure if such a graph representation is useful.
Another way is to represent your graph is use an array for graph node values and represent edges as an adjacency matrix N-by-N where each element is a bit specifying whether there is an edge from node A to node B.
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.
MY CODE:
there is an array in the class "table" to hold newly added book (struct);
add just put in one next to one in the array;
search can use ISBN, title or author, which are all variables in book (struct);
print is supposed to cout the info of book
PROBLEM: print can't print string (variable in book are all string)
MAY NOT BE PROBLEM:
insert,add...this kind of function should work well because when I search some book, it shows "book found"
#include<iostream>
#include<string>
using namespace std;
struct book
{
string isbn;
string title;
string author;
string date;
};
class table
{
public:
//member constant
static const size_t CAPACITY = 30;
//constructor
table() {used = 0;}
//modification
bool insert(book entry);
//constant
size_t hash_isbn(string target_isbn);
size_t hash_title(string target_title);
size_t hash_author(string target_author);
size_t search_isbn(string target_isbn);
size_t search_title(string target_title);
size_t search_author(string target_author);
void print(size_t index);
private:
//member variables
book data[CAPACITY];
size_t used;
};
//modification member functions
bool table::insert(book entry)
{
if(search_isbn(entry.isbn))
return false;
data[used] = entry;
used++;
return true;
}
//constant member functions
size_t table::hash_isbn(string target_isbn)
{
size_t index = 0;
bool found = false;
while((index < used) && (!found))
{
if(data[index].isbn == target_isbn)
{
found = true;
continue;
}
index ++;
}
if(!found)
index = -1;
return index;
}
size_t table::hash_title(string target_title)
{
size_t index = 0;
bool found = false;
while((index < used) && !found)
{
if(data[index].title == target_title)
{
found = true;
continue;
}
index ++;
}
if(index == used)
index = -1;
return index;
}
size_t table::hash_author(string target_author)
{
size_t index = 0;
bool found = false;
while((index < used) && !found)
{
if(data[index].author == target_author)
{
found = true;
continue;
}
index ++;
}
if(index == used)
index = -1;
return index;
}
size_t table::search_isbn(string target_isbn)
{
return hash_isbn(target_isbn)+1;
}
size_t table::search_title(string target_title)
{
return hash_isbn(target_title)+1;
}
size_t table::search_author(string target_author)
{
return hash_isbn(target_author)+1;
}
void table::print(size_t index)
{
cout.flush();
cout<<data[index].title<<endl;
cout<<"Title: "<<data[index].title<<endl;
cout<<"ISBN: "<<data[index].isbn<<endl;
cout<<"Author: "<<data[index].author<<endl;
cout<<"Publication data: "<<data[index].date<<endl;
cout<<endl;
}
//nonmember functions
void add(table t)
{
book entry;
cout<<"Enter author name:"<<endl;
cin>>entry.author;
cout<<endl;
cout<<"Enter book name:"<<endl;
cin>>entry.title;
cout<<endl;
cout<<"Enter ISBN:"<<endl;
cin>>entry.isbn;
cout<<endl;
cout<<"Enter the publication data:"<<endl;
cin>>entry.date;
cout<<endl;
if(t.search_isbn(entry.isbn))
cout<<"==== The book already exists !!! ==="<<endl;///////////////////////输入重复时,此处并未执行
else
t.insert(entry);
}
void search(table t)
{
string option;
cout<<"Seach by ISBN (I), book title (T), or author (A). Choice: ";
cin>>option;
cout<<endl;
while((option != "I") && (option != "T") && (option != "A"))
{
cout<<"Not an accessible option, try again:"<<endl
<<"Seach by ISBN (I), book title (T), or author (A). Choice: ";
cin>>option;
cout<<endl;
}
size_t index;
if(option == "I")
{
string target_isbn;
cout<<"Enter ISBN: ";
cin>>target_isbn;
cout<<endl;
index = t.search_isbn(target_isbn);
}
if(option == "T")
{
string target_title;
cout<<"Enter Title: ";
cin>>target_title;
cout<<endl;
index = t.search_isbn(target_title);
}
if(option == "A")
{
string target_author;
cout<<"Enter Author: ";
cin>>target_author;
cout<<endl;
index = t.search_isbn(target_author);
}
if(index+1)
{
cout<<"Book found"<<endl;
t.print(index);
}
else
cout<<"==== The book does not exist !!! ==="<<endl;
}
int main()
{
table hash_table;
string action;
bool done = false;
while(!done)
{
cout<<"Add a new book (A), search (S), or end program (E)? ";
cin>>action;
cout<<endl;
while((action != "A") && (action != "S") && (action != "E"))
{
cout<<"Not an accessible option, try again:"<<endl
<<"Add a new book (A), search (S), or end program (E)? ";
cin>>action;
cout<<endl;
}
if(action == "A")
add(hash_table);
if(action == "S")
search(hash_table);
if(action == "E")
{
done = true;
continue;
}
}
hash_table.print(0); // this code just try to test my problem in a simple way
system("pause");
return 0;
}
The problem is not with print function or something related with it. In function add(and search too) you pass table object by value. Just pass by reference.
void add(table& t)
// ^