It gets segmentation fault 11 when I tried to inqueue the data in my queue program. I'm using the GCC compiler in my Atom text editor.
#include<iostream>
#include<stdlib.h>
#define MAX 5
using namespace std;
struct queue{
int data[MAX];
int awal, akhir;
}antrean;
void first(){
antrean.awal = -1;
antrean.akhir = -1;
}
bool isfull(){
if(antrean.akhir == MAX-1){
return true;
}else{
return false;
}
}
bool isempty(){
if(antrean.akhir == -1){
return true;
}else{
return false;
}
}
void tampildata(){
if(!isempty()){
for(int i=antrean.awal; i<antrean.akhir; i++){
cout<<antrean.data[i]<<" | ";
}
}
cout<<endl;
}
void inqueue(){
int elemen;
if(isempty()){
cout<<"input data : ";
cin>>elemen;
antrean.data[antrean.akhir] = elemen;
antrean.akhir++;
cout<<"data berhasil ditambah"<<endl;
tampildata();
}else{
cout<<"Queue penuh";
}
}
void dequeue(){
tampildata();
if(!isempty()){
cout<<"mengambil data "<<antrean.data[antrean.awal]<<endl;
for(int i=antrean.awal; i<antrean.akhir; i++){
antrean.data[i]=antrean.data[i+1];
}
antrean.akhir--;
}else{
cout<<"antrean empty";
}
}
void cari(){
if(!isempty() == 1){
int cari;
bool state = false;
cout << "Data yang dicari :";
cin >> cari;
for(int i = antrean.awal; i<antrean.akhir; i++){
if (antrean.data[i] == cari) {
cout << "Data ditemukan pada indeks Ke-:" << antrean.data[i]+1<< endl;
state = true;
break;
}
}
} else{
cout << "Data tidak ditemukan";
}
}
void totalarray(){
int temp = 0;
for(int i=-1; i<antrean.akhir; i++){
temp = temp+antrean.data[i];
}
cout << "Total nilainya :" << temp;
}
int main(){
int pilihan, elemen;
first();
do{
tampildata();
cout<<"1. Init"<<endl<<"2. inQueue"<<endl<<"3. deQueue"<<endl<<"4. tampil data"<<endl<<"5. Cari data"<<endl << "6. Total nilai"<<endl<<"7. Rata-rata Array"<<endl;
cout<<"8. Nilai terbesar"<<endl<<"9. Nilai terkecil"<<endl<<"10. Clear"<<endl<<"11. Keluar";
cout<<"input pilihan :";
cin>>pilihan;
switch(pilihan){
case 1:
first();
break;
case 2:
inqueue();
break;
case 3:
dequeue();
break;
case 4:
tampildata();
break;
case 5:
cari();
break;
case 6:
totalarray();
break;
case 7:
exit(0);
}
}
while(pilihan!=7);
return 0;
}
Your problem is in the value of your counter. You initially set it to -1 (although 0 might make more sense if it has 0 elements?). Then, when you're adding to your queue for the first time you basically want to add an element to the (-1)st place. This causes you to write outside the bounds of the array and a segmentation fault occurs.
antrean.akhir = -1;
...
antrean.data[antrean.akhir] = elemen;
You can simply set the counter to 0 and have it actually count the number of elements in the array.
I have not gone through the rest of the code, so I can't say it won't crash for some other reason later on.
Related
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 have studied the algorithm from Introduction to Algorithm and then
I have written this code. But in my output another value is showing for index 0. and when I use pop function it display 1 instead of 3
#include <iostream>
int top;
void initialise_top(){
top = -1;
}
bool stack_empty(int a[]){
if(top == -1)
return true;
else
return false;
}
void push(int a[], int x, int s){
if(top < s - 1){
top = top + 1;
a[top] = x;
}
else
std::cout << "overflow" << "\n";
}
int pop(int a[]){
if (stack_empty(a) == true)
std::cout << "Underflow" << "\n";
else{
--top;
return a[top+1];
}
}
void display(int a[]){
for(int i = 0;i <= top; i++){
std::cout << a[i] << " ";
}
}
int main()
{
int arr[7];
push(arr,15,7);
push(arr,6,7);
push(arr,2,7);
push(arr,9,7);
push(arr,17,7);
push(arr,3,7);
display(arr);
std::cout << "\n";
int out = pop(arr);
std::cout << pop << "\n";
return 0;
}
Here is the snapshot of the output
enter image description here
In your implementatiton you have "initialise_top()" function.
void initialise_top(){
top=-1;
}
But you don't call it in main function. If you don't call it you can't initialize "top" variable and "top" variable will hold garbage value.
You can read details in here :
Default variable value
And also in theese lines you have some mistakes:
int out=pop(arr);
std::cout<<pop<<"\n";
you must print "out" variable :
std::cout << out << "\n";
You can look to corrected code for your implementation in here :
https://repl.it/JaOd/0
I have this stack array code in C. You can use it as your guide in implementing it to C++.
#include <stdio.h>
#include <stdlib.h>
void push(void);
void pop(void);
int a[5];
int top = -1;
int counter = 0;
int choice;
main() {
do{
printf("*********************************************\nSTACK\nPress the
corresponding button you desire.\n\nPress 1 to push a number to
stack.\nPress 2 to display the current stack.\nPress 3 to pop the current
stack.\nPress 0 to exit.\n\n");
scanf("%d", &choice);
if(choice == 0){
choice = 0;
}
else if(choice == 1){
push();
}
else if(choice == 2){
int i;
printf("Current Stack:\n");
for(i = 0;i <= 4;i++){
printf("%d", a[i]);
}
printf("\n\n");
}
else if(choice == 3){
pop();
}
}while(choice != 0);
}
void push(){
if(top <= 3){
int input;
printf("Enter number to push: ");
scanf("%d", &input);
top = top + 1;
a[top] = input;
int i;
printf("Current Stack:\n");
for(i = 0;i <= 4;i++){
printf("%d", a[i]);
}
printf("\n\n");
}else{
printf("Out of Bounds\n\n");
exit(0);
}
}
void pop(){
if(top >= 0){
printf("You just popped: ");
printf("%d \n\n", a[top]);
a[top] = 0;
printf("Current Stack:\n");
int i;
for(i = 0;i <= 4;i++){
printf("%d", a[i]);
}
printf("\n\n");
top = top - 1;
}else{
printf("Out of Bounds\n\n");
exit(0);
}
}
#include <iostream>
int top;
void initialise_top(){
top=-1;}
bool stack_empty(int a[]){
if(top==-1)
return true;
else
return false;
}
void push(int a[],int x,int s){
if(top<s-1){
top=top+1;
a[top]=x;
}
else
std::cout<<"overflow"<<"\n";
}
int pop(int a[]){
if (stack_empty(a)==true)
std::cout<<"Underflow"<<"\n";
else{
--top;
return a[top+1];
}
}
void display(int a[]){
for(int i=0;i<=top;i++){
std::cout<<a[i]<<" ";
}
}
int main()
{
**initialise_top();**//this statement initialises top=-1
int arr[7];
//std::cout<<stack_empty(arr)<<"\n";
push(arr,15,7);
push(arr,6,7);
push(arr,2,7);
push(arr,9,7);
push(arr,17,7);
push(arr,3,7);
display(arr);
std::cout<<"\n";
int out=pop(arr);
std::cout<<**out**<<"\n";
return 0;
}
1.In your program the value of top=1 when the first element 15 is inserted. due
to this another value is shown for index 0.
So to have top=0, call the function initialise_top(); in main function.
2.To display 3 instead of 1 use
std::cout<<out<<"\n";
Modifications in the program are bold.
I have tried to improve my code. Please tell me if can improve.
#include <iostream>
#define max 1000
class Stack{
int top;
public:
int a[max];
Stack(){
top=-1;
}
bool stack_empty();
void push(int x);
int pop();
void display();
};
bool Stack::stack_empty(){
if(top==-1)
return true;
else
return false;
}
void Stack::push(int x){
int s=max-1;
if(top<s){
top=top+1;
a[top]=x;
}
else
std::cout<<"overflow"<<"\n";
}
int Stack::pop(){
if (stack_empty()==true)
std::cout<<"Underflow"<<"\n";
else{
--top;
return a[top+1];
}
}
void Stack::display(){
for(int i=0;i<=top;i++){
std::cout<<a[i]<<" ";
}
}
int main()
{
Stack stack1;
stack1.push(15);
stack1.push(6);
stack1.push(2);
stack1.push(9);
stack1.push(3);
stack1.display();
std::cout<<"\n";
std::cout<<stack1.pop()<<"\n";
stack1.display();
return 0;
}
array keeps bringing garbage value while it should be empty.following is my
/*
Name: Hotel Room Reservation
Author: Ali Naseem, M. Abbas, M. Hammad, Raza Zaidi
Date: 23-08-16 01:20
Description: This software is about reserving a room in hotel. User will provide its information and his requirement after which software will reserve a room for him.
*/
#include <iostream>
#include <cstring>
using namespace std;
int n=0,j=0,k=0,l=0,c=1,r=1;
void customer();
void roomType();
void admin();
void status();
void bill();
struct credentials{
string user, pass, USER, PASS;
}cr = {} ;
struct rooms //Stucture Variables for Room Details
{
int roomT, noRoom[30], confirm=0;
int roomId[3][10]={{}};
int singleR[10] = {101,102,103,104,105,106,107,108,109,110};
int doubleR[10] = {111,112,113,114,115,116,117,118,119,120};
int suitR[10] = {121,122,123,124,125,126,127,128,129,130};
} room;
struct custDet //Stucture Variables for Customer Details
{
string name[30]={""};
int cnic[30], ID[30], noPer[30], day[30];
} guest;
void customer() //Customer Module
{
bool keep=true;
int opt;
while(keep)
{
if(k>10 && j>10 && l>10)
{
cout<<"\nSorry We dont have any room available";
goto skipCust;
}
cout<<"\nEnter Your Full Name: ";
cin.ignore();
getline(cin,guest.name[n]);
cout<<"\nEnter Your CNIC Number: ";
cin>>guest.cnic[n];
cout<<"\nNumber Of Rooms Required: ";
cin>>room.noRoom[n];
roomType();
if(room.roomT==0)
{
goto skipCust;
}
cout<<"\n\nPlease Enter The Numbers of Persons Will Stay: ";
cin>>guest.noPer[n];
cout<<"\nNumber of Days To Stay: ";
cin>>guest.day[n];
invalid:
cout<<"\n\nPress 1 To Add More Coustomers or 0 To Go To Previous Menu: ";
cin>>room.confirm;
if(room.confirm==1)
{
keep=true;
}
else if(room.confirm==0)
{
keep=false;
}
else
{
cout<<"'\nInvalid Selection.";
goto invalid;
}
}
skipCust:;
}
void roomType() //Reservation Module
{
bool keep=true;
while(keep)
{
cout<<"\nFollowing is the list of types of Room:"<<endl<<endl;
cout<<"Code\tRoom Type \tFares (Per Day)"<<endl;
cout<<"1- \tSingle Room\t1000"<<endl;
cout<<"2- \tDouble Room\t1500"<<endl;
cout<<"3- \tSuit \t3000"<<endl<<endl;
cout<<"(Press 0 to go back)"<<endl;
cout<<"\nSelect Your Room Type: ";
cin>>room.roomT;
if(room.roomT==1)
{
room.roomId[1][c]=room.singleR[j];
cout<<"\nYour Room No. is: "<<room.roomId[1][c];
n++;
j++;
c++;
keep=false;
}
else if(room.roomT==2)
{
room.roomId[2][c]=room.doubleR[k];
cout<<"\nYour Room No. is: "<<room.roomId[2][c];
n++;
k++;
c++;
keep=false;
}
else if(room.roomT==3)
{
room.roomId[3][c]=room.singleR[l];
cout<<"\nYour Room No. is: "<<room.roomId[3][c];
n++;
l++;
c++;
keep=false;
}
else if(room.roomT==0)
{
keep=false;
}
else
{
cout<<"\nInvalid Selection";
}
}
}
void admin() //Admin Module
{
int opt;
bool keep=true;
if(cr.USER.empty()) //To set Login credentials
{
cout<<"\nSIGN UP";
cin.ignore();
cout<<"\nUser: ";
getline(cin,cr.user);
cr.USER=cr.user;
cout<<"\nPass: ";
getline(cin,cr.pass);
cr.PASS=cr.pass;
}
else //If Login credentials are already set
{
cout<<"\nSIGN IN";
cin.ignore();
cout<<"\nUser: ";
getline(cin,cr.user);
cout<<"\nPass: ";
getline(cin,cr.pass);
}
if((cr.user==cr.USER) && cr.pass==cr.PASS)
{
cout<<"\nSigned In Successfully";
}
else
{
cout<<"\nusername or password is incorrect Try Again";
}
while(keep)
{
cout<<"\nRooms Status \t(Press 1)";
cout<<"\nBill \t(Press 2)";
cout<<"\nFor Previous Menu\t(Press 0)"<<endl;
cout<<"Choice: ";
cin>>opt;
if(opt==1)
{
status();
}
else if (opt==2)
{
bill();
}
else if (opt==0)
{
keep=false;
}
else
{
cout<<"\nInvalid Selection";
keep=true;
}
}
}
void status() //Status Module
{
int opt;
bool keep=true;
while(keep)
{
cout<<"\nSelect the room for there status:";
cout<<"\nCode\tRoom Type"<<endl;
cout<<"1- \tSingle Room"<<endl;
cout<<"2- \tDouble Room"<<endl;
cout<<"3- \tSuit "<<endl<<endl;
cout<<"(Press 0 to go back)"<<endl;
cout<<"\nSelect Your Room Type: ";
cin>>opt;
if(opt==1)
{
cout<<"\nRoom\tStatus\n";
for(int i=1; i<=10; i++ )
{
if(room.roomId[1][i]>0)
{
cout<<room.roomId[1][i]<<"\t Occupied\n";
}
}
}
else if(opt==2)
{
cout<<"\nRoom\tStatus\n";
for(int i=1; i<=10; i++ )
{
if(room.roomId[2][i]>0)
{
cout<<room.roomId[2][i]<<"\t Occupied\n";
}
}
}
else if(opt==3)
{
cout<<"\nRoom\tStatus\n";
for(int i=1; i<=10; i++ )
{
if(room.roomId[3][i]>0)
{
cout<<room.roomId[3][i]<<"\t Occupied\n";
}
}
}
else if(opt==0)
{
keep=false;
}
else
{
cout<<"\n Invalid Choice";
keep=true;
}
}
}
void bill()
{
int opt;
cout<<"\nThis is Bill Module";
cout<<"\nPress 0 to go back to previous menu";
cin>>opt;
}
int main()
{
int opt;
bool keep = true;
while(keep)
{
cout<<"\n*************************"<<endl;
cout<< " Hotel Room Reservation "<<endl;
cout<<"*************************"<<endl;
cout<<"Customer (Press 1)"<<endl;
cout<<"Admin (Press 2)"<<endl;
cout<<"Exit (Press 0)"<<endl;
cout<<"Choice: ";
cin>>opt;
if(opt==1)
{
customer();
}
else if(opt==2)
{
admin();
}
else if(opt==0)
{
cout<<"Invlid Selection"<<endl;
keep=false;
}
else
{
cout<<"Invalid Selection"<<endl;
}
}
cout<<endl;
return 0;
}
problem is with the following lines
if(opt==1)
{
cout<<"\nRoom\tStatus\n";
for(int i=1; i<=10; i++ )
{
if(room.roomId[1][i]>0)
{
cout<<room.roomId[1][i]<<"\t Occupied\n";
}
}
}
else if(opt==2)
{
cout<<"\nRoom\tStatus\n";
for(int i=1; i<=10; i++ )
{
if(room.roomId[2][i]>0)
{
cout<<room.roomId[2][i]<<"\t Occupied\n";
}
}
}
else if(opt==3)
{
cout<<"\nRoom\tStatus\n";
for(int i=1; i<=10; i++ )
{
if(room.roomId[3][i]>0)
{
cout<<room.roomId[3][i]<<"\t Occupied\n";
}
}
}
room.roomId[1][i] is empty but room.roomId[2][i] and room.roomId[3][i] brings some garbage value. i could share my whole source code if u need.
this array is supposed to take values from another variable but how can it takes values without assigning it to him.
You have declared int roomId[3][10], but trying to access roomId[3][10]. That's why you are getting garbage values as you can access only from 0 to (size-1) index. The lastmost roomId should be roomId[2][9].
You can increase the size of array in declaration.
int roomId[4][11];
Or,
Instead of using array index from 1 to 10, use 0 to 9.
Just throwing this out there since I was confused. In my for loops filling my 2d array I switched the rows and cols i.e: i and j. So when I went to read them i was getting what looked like good output for the first half, then trash second half.
below i have uploaded a code to check if there parentheses in a string are balanced or not using stacks.It is working for 1 input,but for multiple testcases the correct output is not working.PLEASE HELP.THANKS IN ADVANCE.
int main()
{
int t;
cin >>t;
cin.ignore();
while(t--)
{
{
stack s;
char *st;
st=new char[100];
gets(st);
s.create(strlen(st));
if(!count_elem(st))//counts if the brackets are in pairs or not
cout << "NO" <<endl;
else
func1(s,st);
}
}
return 0;
}
void func1(stack s,char *st)
{
static int i=0,flag=0;
// printf("%d %d\n",i,flag);
if(st[i]=='(' || st[i]=='{' || st[i]=='[')
{
flag=1;
s.push(st[i]);
}
else
{
if(s.isEmpty())
flag=0;
else
{
if(st[i]=='}')
{
//printf("%c\n",s.get_top());
if(s.get_top()=='{')
{
flag=1;
s.pop();
}
else
flag=0;
}
if(st[i]==')')
{
//printf("%c\n",s.get_top());
if(s.get_top()=='(')
{
flag=1;
s.pop();
}
else
flag=0;
}
if (st[i]==']')
{
//printf("%c\n",s.get_top());
if(s.get_top()=='[')
{
flag=1;
s.pop();
}
else
flag=0;
}
}
}
i++;
if(flag==1)
{
if(i<strlen(st))
func1(s,st);
else
cout << "YES"<<endl;
}
else
cout << "NO"<< endl;
}
The problem is...when the program goes from one testcase to another,it does not reinitialize i=0,flag=0...because they have been declared as static variables.What can be done instead is....declare i,flag globally....and assign i=0;flag=0; just before making the first func()call for every testcase....
int main()
{
int t;
cin >>t;
cin.ignore();
while(t--)
{
{
stack s;
char *st;
st=new char[100];
gets(st);
s.create(strlen(st));
if(!count_elem(st))
cout << "NO" <<endl;
else
{
i=0;
flag=0;
func1(s,st);
}
delete []st;
}
}
return 0;
}
This is for an assignment before you tell me not to use an array. Unfortunately I have to.
I've troubleshot this for a good amount of time and I've finally given up and come to ask the smart people here. I know this is something to do with how I'm allocating the array, but I can't figure what's wrong. It goes through the inner loop once and then freeze on the second run. Sorry if I left anything important out. I will add any needed info.
Variables from Card
private:
string *cardRank;
string *suit;
int rankNum;
int value;
Problem Function
void initArray(Card **cPtr)
{
int i;
int j;
int index=0;
cPtr = new Card*[DECK]; //deck is const int 52
for(i=0; i < 4; ++i)
{
for(j=1; j < 14; ++j)
{
cPtr[index] = new Card(j, j, i); //freezes here. does not make it to the first
//function in the constructor
cout << cPtr[index] << endl;
++index;
}
}
}
Constructor
Card::Card(int cRank, int cValue, int suitNum)
{
setRankNum(cRank);
cout << "rank num set\n";
setValue(cValue);
cout << "val set\n";
setSuit(suitNum);
cout << "suit set\n";
setRank(cRank);
cout << "rank set\n";
}
Overloaded <<
ostream &operator << (ostream &strm, Card &aCard)
{
strm << aCard.getRank() << " of " << aCard.getSuit();
return strm;
}
whole program
#include <string>
#include "Card.h"
using namespace std;
const int DECK = 52;
void initArray(Card **&cPtr);
void shufflePArray(Card **pArray);
void determineHand(Card **pArray);
bool isFlush(Card *hand);
bool isStraight(Card *hand);
bool isFour(Card *hand);
bool isThree(Card *hand);
bool isTwo(Card *hand);
void drawHand(Card *hand, Card **pArray);
void displayHand(Card **hand);
int main()
{
Card **cArray;
initArray(cArray);
cout << "done.";
shufflePArray(cArray);
determineHand(cArray);
delete [] cArray;
return 0;
}
void initArray(Card **&cPtr)
{
int i;
int j;
int index=0;
cPtr = new Card*[DECK];
for(i=0; i < 4; ++i)
{
for(j=1; j < 13; ++j)
{ cout << "inner loop " << index << endl;
cPtr[index] = new Card(j, j, i);
cout << cPtr[index] << endl;
++index;
}
}
}
void shufflePArray(Card **pArray)
{
//code here
}
void determineHand(Card ***pArray)
{
Card hand[5];
drawHand(hand, pArray);
displayHand(pArray);
if (isFlush(hand) == true)
{
if(isStraight(hand) == true)
cout << "Straight flush!!!" << endl;
else
cout << "You got a flush!" << endl;
}
else if(isStraight(hand) == true)
{
cout << "You got a straight!" << endl;
}
else if(isFour(hand) == true)
{
cout << "Four of a kind!!!" << endl;
}
else if(isThree(hand)==true)
{
cout << "Three of a kind!" << endl;
}
else if(isTwo(hand) == true)
{
cout << "That's a pair";
}
}
bool isFlush(Card *hand)
{
int i;
int match;
for (i=0; i<5;++i)
{
if (hand[0].getSuit() == hand[i].getSuit())
match++;
}
if (match == 5)
return true;
else
return false;
}
bool isStraight(Card *hand)
{
int match;
for (int i=0; i<5;++i)
{
if (hand[0].getValue() == hand[i].getValue() - 1)
match++;
}
if (match == 5)
return true;
else
return false;
}
bool isFour(Card *hand)
{
int match = 0;
for(int i=0; i<5; ++i)
{
match=0;
for(int j=0;j<5;++j)
{
if (hand[i] == hand[j])
match++;
if (match == 4)
return true;
else
return false;
}
}
}
bool isThree(Card *hand)
{
int match = 0;
for(int i=0; i<5; ++i)
{
match=0;
for(int j=0;j<5;++j)
{
if (hand[i] == hand[j])
match++;
if (match == 3)
return true;
else
return false;
}
}
}
bool isTwo(Card *hand)
{
int match = 0;
for(int i=0; i<5; ++i)
{
match=0;
for(int j=0;j<5;++j)
{
if (hand[i] == hand[j])
match++;
if (match == 2)
return true;
else
return false;
}
}
}
void drawHand(Card *hand, Card **pArray)
{
for(int i=0; i<5;++i)
cout << hand[i];
}
}
{
hand[i] = *pArray[i];
}
}
void displayHand(Card **hand)
{
Card temp;
for (int i = 0; i < 5; ++i)
{
contents of card.h
#ifndef CARD_H
#define CARD_H
#include <string>
#include <iostream>
using namespace std;
class Card
{
private:
string *cardRank;
string *suit;
int rankNum;
int value;
public:
Card();
Card(int cRank, int cValue, int suitNum);
friend ostream &operator << (ostream &strm, Card &aCard);
bool operator > (const Card &aCard);
bool operator < (const Card &aCard);
bool operator == (const Card &aCard);
void setRank(int r);
void setSuit(int s);
void setValue(int v);
void setRankNum(int n);
string getRank();
string getSuit();
int getRankNum();
int getValue();
};
#endif // CARD_H
contents of Card.cpp
#include "Card.h"
#include <string>
#include <iostream>
Card::Card()
{
cardRank = NULL;
suit = NULL;
rankNum = 0;
value = 0;
}
Card::Card(int cRank, int cValue, int suitNum)
{
setRankNum(cRank);
cout << "rank num set\n";
setValue(cValue);
cout << "val set\n";
setSuit(suitNum);
cout << "suit set\n";
setRank(cRank);
cout << "rank set\n";
}
ostream &operator << (ostream &strm, Card &aCard)
{
strm << aCard.getRank() << " of " << aCard.getSuit();
return strm;
}
bool Card::operator > (const Card &aCard)
{
if (aCard.value > value)
return true;
else
return false;
}
bool Card::operator < (const Card &aCard)
{
if (aCard.value < value)
return true;
else
return false;
}
bool Card::operator == (const Card &aCard)
{
if (value == aCard.value)
return true;
else
return false;
}
void Card::setRank(int r)
{
switch(r)
{
case 13:
*cardRank = "Ace";
case 1:
*cardRank = "Two";
case 2:
*cardRank = "Three";
case 3:
*cardRank = "Four";
case 4:
*cardRank = "Five";
case 5:
*cardRank = "Six";
case 6:
*cardRank = "Seven";
case 7:
*cardRank = "Eight";
case 8:
*cardRank = "Nine";
case 9:
*cardRank = "Ten";
case 10:
*cardRank = "Jack";
case 11:
*cardRank = "Queen";
case 12:
*cardRank = "King";
}
}
void Card::setSuit(int s)
{
if(s==0){
*suit = "Hearts";
cout << "suit set";}
else if(s==1)
*suit = "Diamonds";
else if (s==2)
*suit = "Clubs";
else if (s==3)
*suit = "Spades";
else
cout << "Invalid suit num.";
}
void Card::setValue(int v)
{
if (v > 0)
value = v;
}
void Card::setRankNum(int n)
{
rankNum = n;
}
string Card::getRank()
{
return *cardRank;
}
string Card::getSuit()
{
return *suit;
}
int Card::getRankNum()
{
return rankNum;
}
int Card::getValue()
{
return value;
}
One possible reason for your troubles is that you are dereferencing a NULL pointer:
void Card::setRank(int r)
{
switch(r)
{
case 13:
*cardRank = "Ace";
case 1:
*cardRank = "Two";
//...
The cardRank is NULL. You now try to dereference a NULL pointer. Unless I missed something, where is the call to "cardRank = new std::string;"?
But that brings up a bigger point -- in your comment you stated that your professor wants you to use pointers. But honestly, there is no reason whatsoever to use pointers for those string members -- absolutely none.
You do need pointers to implement your dynamic array, but that's it. Either you are reading the professor's intentions incorrectly, or the professor needs to get another profession.
You're passing a pointer to a pointer as value in : initArray(Card **cPtr), apparently your intention is to change it (i.e return the allocated Card array.
I cannot really say what is happening exactly but some memory gets overwritten, the return address in the stack probably
Anyway either change it to reference i.e. initArray(Card **&cPtr) or use initArray(Card ***cPtr) and change the code accordingly.
The second problem in the use of strings, change string *cardRank to string cardRank and suit as well, you don't need pointers to strings (it's not like char*, those are objects any way, the assignments should be changed from *cardRank = "Ace" to cardRank = "Ace"