C++ Printing Values In Vector Based Binary Tree After Insertion - c++

I am tasked with storing a binary tree within a vector. Within each node is stored an int ID, int Age, and a string name.
The nodes are stored and organized within the vector by ID.
When storing the binary tree within a vector, I am using the algorithm 2i and 2i+1 to dictate a node's left and right child respectively.
I have managed to create an insert method that I believe satisfies these conditions, however for some reason, when attempting to print the values of my vector, I appear to get negative values. For this particular example, I insert the following values
50 21 Tim
75 22 Steve
30 40 Eric
20 35 Mary
100 60 Judy
After inserting these four values, I attempt to use my find() method to find Eric, in which my program returns "Not Found!"
I run my report() function to find that all the values stored within my vector are large negative valued IDs.
Is there a particular reason for this? Find()
Report()
Here is my code.
#include "BinaryTree.h"
#include <string>
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int index = 0;
struct Node
{
int ID;
int age;
string name;
Node()
{
}
Node(int id, int Age, string nm)
{
this->ID = id;
this->age = Age;
this->name = nm;
}
};
vector<Node> binaryTree(30);
BST::BST()
{
}
void BST::start()
{
int choice;
cout << "What would you like to do?" << endl;
cout << "1. Add a node to the tree" << endl;
cout << "2. Delete a node from the tree" << endl;
cout << "3. Find a node in the tree" << endl;
cout << "4. Report the contents of the tree" << endl;
cout << "5. Exit program" << endl;
cin >> choice;
if (choice == 1)
{
insert();
}
if (choice == 2)
{
Delete();
}
if (choice == 3)
{
find();
}
if (choice == 4)
{
report();
}
}
void BST::insert()
{
int ID;
int AGE;
string NAME;
int root = 1;
bool success = false;
cout << "Please enter the ID number, age and name:" << endl;
do
{
cin >> ID >> AGE >> NAME;
} while (ID < 0);
Node *tree = new Node(ID, AGE, NAME);
if (index = 0)
{
binaryTree[1] = *tree;
}
if (index > 0)
{
do
{
if (tree->ID > binaryTree.at(root).ID)
{
root = 2 * root + 1;
}
if (tree->ID < binaryTree.at(root).ID)
{
root = 2 * root;
}
if (binaryTree.at(root).ID == NULL)
{
binaryTree.at(root) = *tree;
success = true;
}
} while (!success);
}
index++;
delete tree;
start();
}
void BST::Delete()
{
int input_id;
cout << "What is the ID of the person to be deleted" << endl;
cin >> input_id;
for (unsigned int i = 0; i < binaryTree.size(); i++)
{
if (input_id == binaryTree.at(i).ID)
binaryTree.erase(binaryTree.begin() + i);
}
cout << " " << endl;
start();
}
void BST::find()
{
int key;
bool found = 0;
cout << "What's the ID?" << endl;
cout << " " << endl;
cin >> key;
for (unsigned int i = 0; i < binaryTree.size(); i++)
{
if (binaryTree.at(i).ID == key)
{
cout << "The ID is " << binaryTree.at(i).ID << endl;
cout << "The age ID " << binaryTree.at(i).age << endl;
cout << "The name is " <<binaryTree.at(i).name << endl;
cout << " " << endl;
found = true;
}
if (found == false)
{
cout << "Not found." << endl;
cout << "" << endl;
break;
}
}
start();
}
void BST::report()
{
cout << "The contents of the tree are" << endl;
cout << " " << endl;
for (unsigned int i = 0; i < binaryTree.size(); i++)
{
int level = 0;
if (i == 0) level = 0;
if (i == 1 || i == 2) level = 1;
if (i >= 3 && i <= 6) level = 2;
if (i >= 7 && i <= 14) level = 3;
//TODO complete list
cout << binaryTree.at(i).ID << " " << binaryTree.at(i).age << " " << &binaryTree.at(i).name << " " << level << endl;
}
}
Would appreciate the suggestions/help!
Thanks!

I think issues is with indexing here
In insert() you created binary tree with root at index in but in report() function you started output from index 0. I have no idea what binaryTree.at(int) do.
But in find() your error is due to the fact that you have included if(found == 0) inside the loop. This means that it will break the loop if 1st element of tree is not the element you are searching. Use this code instead
void BST::find()
{
int key;
bool found = 0;
cout << "What's the ID?" << endl;
cout << " " << endl;
cin >> key;
for (unsigned int i = 0; i < binaryTree.size(); i++)
{
if (binaryTree.at(i).ID == key)
{
cout << "The ID is " << binaryTree.at(i).ID << endl;
cout << "The age ID " << binaryTree.at(i).age << endl;
cout << "The name is " <<binaryTree.at(i).name << endl;
cout << " " << endl;
found = true;
}
}
if (found == false)
{
cout << "Not found." << endl;
cout << "" << endl;
}
start();
}

Related

How to access variables within a struct while iterating through it?

In my program, I have a vector of structs, and I'm trying to iterate through the vector while accessing the properties of each struct. However, the way I'm trying to do this doesn't seem to work. The struct in question is called "person", and it has properties including "Name" and "PartyID", which are the ones I'm trying to access.
I read somewhere online you could do this using pointers to the iterator, so that's what I tried to do (*it.Name and *it.PartyID), but the program won't compile. What am I doing wrong? Here are the errors I'm getting (using G++ to compile the program):
And here is the code I've written:
// DelibDem.cpp : Defines the entry point for the application.
//
#include "DelibDem.h"
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <vector>
//initializing variables
using namespace std;
bool continue_ = true;
string name = "";
string partyID = "";
int numD = 0;
int numR = 0;
int difference = 0;
int vectorSize = 0;
int newVectorSize = 0;
int vectorPos = 0;
int demPos = 0;
int repPos = 0;
struct person{
string Name;
string PartyID;
string equivalentName;
string equivalenceClass;
};
vector<person> Sample;
int main()
{
//user adds people to the vector
while (continue_ == true) {
string personName;
string personPartyID;
string answer;
person inputtedPerson;
cout << "Enter a person's name: ";
std::getline(cin, personName);
//cout << personName;
cout << "Enter the person's party ID (D or R): ";
std::getline(cin, personPartyID);
//cout << personPartyID;
if (personPartyID == "D") person inputtedPerson = { personName, personPartyID, "", "Republicans" };
else person inputtedPerson = { personName, personPartyID, "", "Democrats" };
Sample.at(vectorPos) = inputtedPerson;
//cout << "{{" << Sample.at(0).Name << ", " << Sample.at(0).PartyID << ", " << Sample.at(0).equivalentName << ", " << Sample.at(0).equivalenceClass << "}\n";
//for (int i = 1; i < Sample.size(); i++) {
// cout << ", {" << Sample.at(i).Name << ", " << Sample.at(i).PartyID << ", " << Sample.at(i).equivalentName << ", " << Sample.at(i).equivalenceClass << "}\n";
//}
//cout << "}";
vectorPos++;
cout << "Do you wish to add more people? (Y/N) ";
cin >> answer;
if (answer == "N") continue_ = false;
cin.ignore();
}
//The number of Democrats in the sample is stored in numD. The number of Republicans is stored in numR.
for (auto& element : Sample)
{
if (element.PartyID == "D") numD++;
else numR++;
}
//print the number of Democrats and Republicans
cout << numD;
cout << numR;
//determine if an equivalence relation exists
if (numD == numR) cout << "An equivalence relation is possible" << endl;
else {
cout << "An equivalence relation is not possible, because ";
if (numD > numR) {
cout << "There are " << numD - numR << " more Democrats than Republicans" << endl;
int difference = numD - numR;
while (difference != 0) {
string specifiedName;
vectorSize = Sample.size();
cout << "Which Democrat do you want to remove from the sample?" << endl;
cin >> specifiedName;
for (std::vector<person>::iterator it = Sample.begin(); it != Sample.end(); ++it) //this is the part I'm asking about
{
if (*it.Name == specifiedName && *it.PartyID == "D") {
Sample.erase(it);
break;
}
}
newVectorSize = Sample.size();
if (vectorSize == newVectorSize) cout << "The requested person is not one of the Democrats in the sample. Please try again." << endl;
else difference--;
}
}
else {
cout << "There are " << numR - numD << " more Republicans than Democrats" << endl;
int difference = numR - numD;
while (difference != 0) {
string specifiedName;
vectorSize = Sample.size();
cout << "Which Republican do you want to remove from the sample?" << endl;
cin >> specifiedName;
for (std::vector<person>::iterator it = Sample.begin(); it != Sample.end(); ++it)
{
if (*it.Name == specifiedName && *it.PartyID == "R") {
Sample.erase(it);
break;
}
}
newVectorSize = Sample.size();
if (vectorSize == newVectorSize) cout << "The requested person is not one of the Republicans in the sample. Please try again." << endl;
else difference--;
}
}
cout << "The number of Democrats and Republicans is now equal and an equivalence relation is possible." << endl;
}
//print the properties of each element in the sample
for (auto& element : Sample)
{
cout << element.Name << endl;
cout << element.PartyID << endl;
cout << element.equivalentName << endl;
cout << element.equivalenceClass << endl;
cout << "\n";
}
//creating two vectors containing only the Democrats and Republicans, respectively
vector<person> Democrats;
vector<person> Republicans;
for (auto& element : Sample)
{
if (element.PartyID == "D") {
Democrats.at(demPos) = element;
demPos++;
}
else {
Republicans.at(repPos) = element;
repPos++;
}
}
//assigning each Democrat to a Republican and vice versa
for (int i = 0; i < Democrats.size(); i++)
{
Democrats.at(i).equivalentName = Republicans.at(i).Name;
}
for (int i = 0; i < Republicans.size(); i++)
{
Republicans.at(i).equivalentName = Democrats.at(i).Name;
}
return 0;
//printing the properties of each element in the sample again
for (auto& element : Sample)
{
cout << element.Name << endl;
cout << element.PartyID << endl;
cout << element.equivalentName << endl;
cout << element.equivalenceClass << endl;
cout << "\n";
}
}

Display Array User Input from Function

This is my code at the moment. It is a lottery game and I get user input for 7 numbers and do not allow duplicates (same goes with the random generated). I need to display the user's numbers and the winning random numbers at the end of the main next to LOTTO RESULTS and WINNING NUMBERS.
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <string>
using namespace std;
void getLottoPicks(int userNums[], int size);
void genWinNums(int winNums[], int size);
int main()
{
const int size = 7;
int UserTicket[size];
int WinningNums[size];
char selection;
string name;
do
{
cout << "LITTLETON CITY LOTTO MODEL: " << endl;
cout << "---------------------------" << endl;
cout << "1) Play Lotto" << endl;
cout << "q) Quit Program" << endl;
cout << "Please make a selection : " << endl;
cin >> selection;
if (selection == '1')
{
cout << "Please enter your name: " << endl;
cin.ignore();
getline(cin, name);
getLottoPicks(UserTicket, size);
genWinNums(WinningNums, size);
cout << name << "'s LOTTO RESULTS" << endl;
cout << "----------------------" << endl;
cout << "WINNING TICKET NUMBERS : " << endl;
cout << name << "'s TICKET : " << endl;
}
else if (selection == 'q')
{
cout << "You have chosen to quit the program. Thank you for using!" << endl;
}
else
{
cout << "Invalid selection. Please try again." << endl;
}
} while (selection != 'q');
return 0;
}
void getLottoPicks(int userNums[], int size)
{
for (int times = 0; times < size; times++)
{
int input;
cout << "selection #" << times + 1 << ": " << endl;
cin >> input;
bool isNotDuplicate = true;
for (int i = 0; i < times; i++)
{
if (userNums[i] == input)
{
isNotDuplicate = false;
}
}
if (isNotDuplicate == true)
{
userNums[times] = input;
}
else
{
cout << "You already picked this number. Please enter a different number: " <<
endl;
times--;
}
}
}
void genWinNums(int winNums[], int size)
{
srand((unsigned int)time(NULL));
for (int times = 0; times < size; times++)
{
int i;
bool isNotDuplicate = true;
while (isNotDuplicate)
{
isNotDuplicate = false;
i = 1 + rand() % 40;
for (int j = 0; j < times; j++)
{
if (i == winNums[j])
{
isNotDuplicate = true;
}
}
}
winNums[times] = i;
}
}
It seems you might be new to programming so here you go, your working program:
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <string>
using namespace std;
void getLottoPicks(int userNums[], int size);
void genWinNums(int winNums[], int size);
int main()
{
const int size = 7;
int UserTicket[size];
int WinningNums[size];
char selection;
string name;
do
{
cout << "LITTLETON CITY LOTTO MODEL: " << endl;
cout << "---------------------------" << endl;
cout << "1) Play Lotto" << endl;
cout << "q) Quit Program" << endl;
cout << "Please make a selection : " << endl;
cin >> selection;
if (selection == '1')
{
cout << "Please enter your name: " << endl;
cin.ignore();
getline(cin, name);
getLottoPicks(UserTicket, size);
genWinNums(WinningNums, size);
cout << name << "'s LOTTO RESULTS" << endl;
cout << "----------------------" << endl;
cout << "WINNING TICKET NUMBERS : " << endl;
for(int i = 0; i < size; i++){
cout << WinningNums[i] << " ";
}
cout << endl;
cout << name << "'s TICKET : " << endl;
for(int i = 0; i < size; i++){
cout << UserTicket[i] << " ";
}
cout << endl;
}
else if (selection == 'q')
{
cout << "You have chosen to quit the program. Thank you for using!" << endl;
}
else
{
cout << "Invalid selection. Please try again." << endl;
}
} while (selection != 'q');
return 0;
}
void getLottoPicks(int userNums[], int size)
{
for (int times = 0; times < size; times++)
{
int input;
cout << "selection #" << times + 1 << ": " << endl;
cin >> input;
bool isNotDuplicate = true;
for (int i = 0; i < times; i++)
{
if (userNums[i] == input)
{
isNotDuplicate = false;
}
}
if (isNotDuplicate == true)
{
userNums[times] = input;
}
else
{
cout << "You already picked this number. Please enter a different number: " <<
endl;
times--;
}
}
}
void genWinNums(int winNums[], int size)
{
srand((unsigned int)time(NULL));
for (int times = 0; times < size; times++)
{
int i;
bool isNotDuplicate = true;
while (isNotDuplicate)
{
isNotDuplicate = false;
i = 1 + rand() % 40;
for (int j = 0; j < times; j++)
{
if (i == winNums[j])
{
isNotDuplicate = true;
}
}
}
winNums[times] = i;
}
}
As you can see, it is pretty easy to loop through an array. Maybe have a look at this for more info on arrays.
Most of the examples show "classic" C++, instead of the more modern variants.
So here's my take on your code :
#include <algorithm>
#include <array>
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <string>
// compile time constant, in many C++ examples this is done with a #define/MACRO
constexpr int number_of_lotto_numbers = 7;
constexpr char play_lotto_char = '1';
constexpr char quit_lotto_char = 'q';
// use std::array instead of int values[]; since this has automatic bound checking!
// no reading/writing beyond array limits is allowed
// I use, using here to make code a bit more readable further down the line
// it lets code show intent instead of implementation
using lotto_numbers_t = std::array<int, number_of_lotto_numbers>;
// do not return arrays by passing arguments, just return an array
// don't worry about this making extra (class) copies c++ knows how to optimize this
lotto_numbers_t get_lotto_picks()
{
lotto_numbers_t lotto_numbers;
auto lotto_numbers_entered{ 0 };
while ( lotto_numbers_entered < number_of_lotto_numbers )
{
int input{ 0 };
std::cout << "selection #" << lotto_numbers_entered + 1 << ": " << std::endl;
std::cin >> input;
// use std::find for finding items in collections, if it finds the end of a collection then
// the value is not found.
if (std::find(lotto_numbers.begin(), lotto_numbers.end(), input) == lotto_numbers.end())
{
// lotto number not found so add it
lotto_numbers[lotto_numbers_entered] = input;
lotto_numbers_entered++;
}
else
{
// lotto number already in array so do not add it but give a message
std::cout << "You already entered this number, try another number" << std::endl;
}
}
return lotto_numbers;
}
lotto_numbers_t generate_winning_numbers()
{
lotto_numbers_t lotto_numbers;
auto lotto_numbers_generated{ 0 };
std::srand((unsigned int)time(NULL));
do
{
int new_number = (std::rand() % 40) + 1;
if (std::find(lotto_numbers.begin(), lotto_numbers.end(), new_number) == lotto_numbers.end())
{
// number not yet found
lotto_numbers[lotto_numbers_generated] = new_number;
lotto_numbers_generated++;
}
} while (lotto_numbers_generated < number_of_lotto_numbers);
return lotto_numbers;
}
void play_lotto()
{
char selection{ 0 }; // always initialize variables!
std::string name;
do
{
std::cout << "LITTLETON CITY LOTTO MODEL: " << std::endl;
std::cout << "---------------------------" << std::endl;
std::cout << "1) Play Lotto" << std::endl;
std::cout << "q) Quit Program" << std::endl;
std::cout << "Please make a selection : " << std::endl;
std::cin >> selection;
if (selection == play_lotto_char)
{
std::cout << "Please enter your name: " << std::endl;
std::cin.ignore();
std::getline(std::cin, name);
auto picked_numbers = get_lotto_picks();
auto winning_numbers = generate_winning_numbers();
std::cout << name << "'s LOTTO RESULTS" << std::endl;
std::cout << "----------------------" << std::endl;
std::cout << "WINNING TICKET NUMBERS : " << std::endl;
for (const auto number : winning_numbers)
{
std::cout << number << " ";
}
std::cout << std::endl;
std::cout << name << "'s TICKET : " << std::endl;
for (const auto number : picked_numbers)
{
std::cout << number << " ";
}
std::cout << std::endl;
if (picked_numbers == winning_numbers)
{
std::cout << "you have won!" << std::endl;
}
}
else if (selection == quit_lotto_char)
{
std::cout << "You have chosen to quit the program. Thank you for using!" << std::endl;
}
else
{
std::cout << "Invalid selection. Please try again." << std::endl;
}
} while (selection != quit_lotto_char);
}
Don't hesitate to ask questions on this code if you have any :)

Moving object from a stack to an array C++ [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
Hey guys so I am writing some coursework and I am almost there, in my code I create a treasure chest and a bag for the player. When the Player is shown the items in the chest they are asked to keep the items which are then stored in there bag or discard the items.
While testing my code I have noticed that the item the player is being shown is not the one that then stores in the bag, almost like the bag is taking from an invisible stack. Then at the end when I call the players bag it still shows as empty as if no items where ever stored????
Please can someone tell me where I am going wrong and how I might resolve it???
These are the specific sections of code that is causing the bug:
void PrintTreasureChest()
{
//TreasureChest A;
int j;
for (j = 1; j < 5; j++)
{
cout << "Item " << j << " in your chest is: " << endl;
cout << "Name:" << (TreasureChest().Chest.top()).Name << endl;
cout << "Rarity out of 3: " << (TreasureChest().Chest.top()).Rarity << endl;
cout << "Part of a set: " << (TreasureChest().Chest.top()).Set << endl;
cout << " " << endl;
PlayerChoice(A);
TreasureChest().Chest.pop();
cout << " " << endl;
}
cout << " " << endl;
cout << "This chest is now empty" << endl;
cout << " " << endl;
cout << " " << endl;
cout << "Items in bag: " << endl;
//Game().ShowRucksack();
return;
}
void PlayerChoice()
{
char Answer;
cout << "If you want to keep the item press Y" << endl;
cout << "If you want to discard the item press N" << endl;
cin >> Answer;
while (Answer == 'Y' || Answer == 'y')
{
cout << "Item stored in your bag" << endl;
StoreItem();
return;
}
while (Answer == 'N' || Answer == 'n')
{
cout << "Item was discared from the Treasure Chest" << endl;
return;
}
while (Answer != 'y' || Answer != 'Y' || Answer != 'N' || Answer != 'n')
{
cout << "To decide press Y for accept OR press N for Decline" << endl;
cin >> Answer;
if (Answer == 'Y' || Answer == 'y') {
cout << "Item stored in your bag" << endl;
//store item in bag
return;
}
else (Answer == 'N' || Answer == 'n'); {
cout << "Item was discared from the Treasure Chest" << endl;
return;
}
return;
}
}
void StoreItem()
{
int dim = 10;
int P = index(Rucksack, dim);
Rucksack[P] = A.Chest.top();
cout << "Item placed in your Bag: " << Rucksack[P].Name << endl;
return;
}
Here is the whole code:
// Loot Class v11.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <string>
#include <stdlib.h>
#include <time.h>
#include <stack>
#include <vector>
#define LootNumber 14
using namespace std;
// the 3 arrays initialise the 3 stats of each item
string NameOption[] = { "Stone", "Leather Gloves", "Dragon Gauntlets", "Chair Leg", "Dragon Scale Helmet", "Pebble", "Rusted Breastplate", "Dragon Breastplate", "Empty Bottle", "Chainmail Trousers", "Dragon Skin Trousers", "Broken Stick", "Dagger", "Dragons Sword" };
int RarityOption[] = { 0, 1, 3, 0, 3, 0, 2, 3, 0, 2, 3, 1, 2, 3 };
bool SetOption[] = { 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1 };
// this class is grouping Name, Rarity and Set. Resulting in every Loot object made, contains 3 variables
class Loot
{
public:
string Name;
int Rarity;
bool Set;
// constructor initialises each of the feilds
Loot(string N, int R, bool S)
{
Name = N;
Rarity = R;
Set = S;
}
// default constructor
Loot()
{
Name = "Empty";
Rarity = 0;
Set = false;
}
// Prints a randomly selected item of loot to the screen, used to check randomisation and that all loot variables print in the correct order
void PrintLoot()
{
int i = rand() % LootNumber;
Loot A(NameOption[i], RarityOption[i], SetOption[i]);
cout << "Loot item: " << A.Name << endl;
cout << "Rarity out of 3: " << A.Rarity << endl;
cout << "Part of set: " << A.Set << endl;
}
};
// enables the creation of a container to stack Loot items in
class TreasureChest
{
public:
stack<Loot> Chest;
// stacks 4 random items in the chest
TreasureChest()
{
int i = rand() % LootNumber;
int j = rand() % LootNumber;
int k = rand() % LootNumber;
int h = rand() % LootNumber;
Chest.push(Loot(NameOption[j], RarityOption[j], SetOption[j]));
Chest.push(Loot(NameOption[k], RarityOption[k], SetOption[k]));
Chest.push(Loot(NameOption[i], RarityOption[i], SetOption[i]));
Chest.push(Loot(NameOption[h], RarityOption[h], SetOption[h]));
}
// prints full contents of Treasure Chest to screen
void ShowFullChest()
{
int i;
for (i = 1; i < 5; i++)
{
cout << "Item: " << i << endl;
cout << "Name:" << TreasureChest().Chest.top().Name << endl;
cout << "Rarity out of 3: " << TreasureChest().Chest.top().Rarity << endl;
cout << "Part of a set: " << TreasureChest().Chest.top().Set << endl;
TreasureChest().Chest.pop();
}
}
};
// Creates container for player to store their chosen Loot items
class PlayerRuckSack
{
public:
Loot Rucksack[10];
// default constructor initialising each array
PlayerRuckSack()
{
for (int i = 0; i < 10; i++)
{
Rucksack[i] = { "Empty", 0, false };
}
};
// prints contents of a rucksack to the screen to allow the player to see what they have collected
void ShowRucksack()
{
for (int i = 0; i < 10; i++)
{
cout << Rucksack[i].Name << " " << Rucksack[i].Set << " " << Rucksack[i].Rarity << " " << endl;
}
}
// replaces an each array with items of Loot and prints when all arrays have been replaced
int index(Loot x[], int n)
{
int i = 0;
int index;
while (x[i].Name != "empty" && 0 && false && i < n)
{
i++;
index = i;
return index;
}
while (i == n)
{
cout << "BAG FULL" << endl;
}
}
};
// For runing the game
class Game : public PlayerRuckSack
{
public:
string PlayerName;
TreasureChest A;
Game()
{
PlayerName = "User 1";
}
Game(string U)
{
PlayerName = U;
}
// intro message to start game
void StartGame()
{
cout << "Welcome to the Cave of Luck" << endl;
cout << "What is your name brave warrior" << endl;
cin >> PlayerName;
cout << PlayerName << " There are 3 Treasure Chests in this cave" << endl;
cout << "Treasure Chests contain many different items" << endl;
cout << "However it appears your bag is small and can only hold 10 items in total" << endl;
cout << "Choose wisley " << PlayerName << endl;
cout << "Good Luck!!" << endl;
cout << " " << endl;
cout << " " << endl;
}
//Gives player choise whether to keep or discard each loot item
void PlayerChoice()
{
char Answer;
cout << "If you want to keep the item press Y" << endl;
cout << "If you want to discard the item press N" << endl;
cin >> Answer;
while (Answer == 'Y' || Answer == 'y')
{
cout << "Item stored in your bag" << endl;
StoreItem();
return;
}
while (Answer == 'N' || Answer == 'n')
{
cout << "Item was discared from the Treasure Chest" << endl;
return;
}
while (Answer != 'y' || Answer != 'Y' || Answer != 'N' || Answer != 'n')
{
cout << "To decide press Y for accept OR press N for Decline" << endl;
cin >> Answer;
if (Answer == 'Y' || Answer == 'y') {
cout << "Item stored in your bag" << endl;
//store item in bag
return;
}
else (Answer == 'N' || Answer == 'n'); {
cout << "Item was discared from the Treasure Chest" << endl;
return;
}
return;
}
}
// Prints the top of TreasureChest to the screen plus uses Playerchoise() after each item is shown
void PrintTreasureChest()
{
//TreasureChest A;
int j;
for (j = 1; j < 5; j++)
{
cout << "Item " << j << " in your chest is: " << endl;
cout << "Name:" << (TreasureChest().Chest.top()).Name << endl;
cout << "Rarity out of 3: " << (TreasureChest().Chest.top()).Rarity << endl;
cout << "Part of a set: " << (TreasureChest().Chest.top()).Set << endl;
cout << " " << endl;
PlayerChoice(A);
TreasureChest().Chest.pop();
cout << " " << endl;
}
cout << " " << endl;
cout << "This chest is now empty" << endl;
cout << " " << endl;
cout << " " << endl;
cout << "Items in bag: " << endl;
//Game().ShowRucksack();
return;
}
// informs player another chest is coming
void NextChest()
{
cout << "Your next chest contains: " << endl;
cout << " " << endl;
}
// Prints end Game message
void EndGame()
{
cout << " " << endl;
cout << " " << endl;
cout << "You have opened all the Chests, come back soon to the Cave of Treasures" << endl;
cout << " THANKYOU FOR PLAYING" << endl;
}
void StoreItem()
{
int dim = 10;
int P = index(Rucksack, dim);
Rucksack[P] = A.Chest.top();
cout << "Item placed in your Bag: " << Rucksack[P].Name << endl; //B.Rucksack[P].Set << B.Rucksack[P].Rarity << endl;
return;
}
};
int main()
{
Game A;
//TreasureChest A;
PlayerRuckSack B;
//A.StartGame();
srand(time(NULL));
A.PrintTreasureChest();
for (int i = 0; i < 10; i++)
{
cout << B.Rucksack[i].Name << " " << B.Rucksack[i].Set << " " << B.Rucksack[i].Rarity << " " << endl;
}
//A.NextChest();
A.EndGame();
//TreasureChest A;
//PlayerRuckSack B;
//int dim = 10;
//int P = index(B.Rucksack, dim);
//B.Rucksack[P] = A.Chest.top();
//cout << "Item in your Bag " << B.Rucksack[P].Name << B.Rucksack[P].Set << B.Rucksack[P].Rarity << endl;
//cout << P << endl;
return 0;
}
I know why nothing is stored in your Rucksack
int index(Loot x[], int n)
{
int i = 0;
int index;
while (x[i].Name != "empty" && 0 && false && i < n)
{
i++;
index = i;
return index;
}
while (i == n)
{
cout << "BAG FULL" << endl;
}
}
Take a careful look at this line:
while (x[i].Name != "empty" && 0 && false && i < n)
&& 0 && false? Both 0 and false mean this is always false and the Rucksack will be reported as empty no matter what.
Then the code will fall out the bottom of index() without returning a value.
After that program behaviour is undefined because you use a return value that was not returned. Any craziness might come after that.
Fix that and come back with another question if you can't figure out your other problem.
It is currently a bit vague.

Editing a Node in a binary tree structure [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
)
I'm working on a code... almost finished but I'm stuck with one last thing,
I need to find a way to edit a client's info when the user wishes to.
this is my code... any one can tell me what's wrong please? :
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
ifstream infile;
ofstream outfile;
struct INFO {
int id;
string name;
unsigned balance;
long phone;
};
class Node
{
public:
INFO data;
Node *left;
Node *right;
Node() {
data.id = 0;
data.name = "NULL";
data.phone = 0;
data.balance = 0;
}
Node(INFO a)
{
data = a;
left = 0;
right = 0;
}
};
class Tree
{
public:
Node *root;
INFO inf;
Node *zero;
Tree()
{
root = 0;
}
bool insert(INFO inf)
{
if (root == 0)
{
root = new Node(inf);
return true;
}
Node *p = root;
Node *q = root;
while (p != 0)
{
q = p;
if (p->data.id == inf.id)
return false;
if (p->data.id > inf.id)
p = p->left;
else
p = p->right;
}
if (inf.id < q->data.id)
q->left = new Node(inf);
else
q->right = new Node(inf);
return true;
}
bool searchid(Node *p, int y)
{
if (p != 0) {
if (p->data.id == y) {
cout << "ID: ";
cout << p->data.id << "\t";
cout << "Name: ";
cout << p->data.name << "\t";
cout << "Balance: ";
cout << p->data.balance << "\t";
cout << "Phone number: ";
cout << p->data.phone << endl;
cout << "_________________" << endl;
return true;
}
}
if (p->left != 0) {
if (searchid(p->left, y)) {
return true;
}
}
if (p->right != 0) {
if (searchid(p->right, y)) {
return true;
}
}
return false;
}
Node SAD(int id) {
Node *p = root;
if (p->data.id == id) {
Node *q = p;
return *p;
}
if (p->left != 0)
SAD(p->left->data.id);
if (p->right != 0)
SAD(p->right->data.id);
return *zero;
}
void edit(int q) {
Node p = SAD(q);
cout << "The ID is: " << p.data.id << endl;
cout << "The account owner: ";
cout << p.data.name << endl;
cout << "Do you want to edit the owner?(Y/N) ";
char x;
cin >> x;
if (x == 'Y' || x == 'y') {
string New;
cout << "Enter the new owner name: ";
cin >> New;
p.data.name = New;
}
cout << "The Balance in the account is: ";
cout << p.data.balance << endl;
cout << "Do you want to edit the balance?(Y/N) ";
cin >> x;
if (x == 'Y' || x == 'y') {
int New;
cout << "Enter the new Balance: ";
cin >> New;
p.data.balance = New;
}
cout << "The phone number is: ";
cout << p.data.phone << endl;
cout << "Do you want to edit the phone number?(Y/N) ";
cin >> x;
if (x == 'Y' || x == 'y') {
long New;
cout << "Enter the new phone number";
cin >> New;
p.data.phone = New;
}
cout << p.data.id << " " << p.data.name << " " << p.data.balance << " " << p.data.phone << endl;
insert(p.data);
}
void print(Node *p)
{
if (p != 0) {
cout << "ID: ";
cout << p->data.id << "\t";
cout << "Name: ";
cout << p->data.name << "\t";
cout << "Balance: ";
cout << p->data.balance << "\t";
cout << "Phone number: ";
cout << p->data.phone << endl;
cout << "_______________________________________________________________" << endl<<endl;
}
if (p->left != 0)
print(p->left);
if (p->right != 0)
print(p->right);
}
void store(Node *p)
{
if (p != 0) {
outfile << "ID: ";
outfile << p->data.id << " ";
outfile << "Name: ";
outfile << p->data.name << " ";
outfile << "Balance: ";
outfile << p->data.balance << " ";
outfile << "Phone number: ";
outfile << p->data.phone << endl;
outfile << "_______________________________________________________________" << endl;
}
if (p->left != 0)
store(p->left);
if (p->right != 0)
store(p->right);
}
bool searchname(Node *p, string x)
{
Node *q = root;
q = p;
while (p != 0) {
if (p->data.name == x) {
cout << "ID: " << p->data.id << "\t";
cout << "Name: " << p->data.name << "\t";
cout << "Balance: " << p->data.balance << "\t";
cout << "Phone number: " << p->data.phone << endl;
}
else {
}
}
}
};
void main()
{
outfile.open("clients.txt");
int opt;
Tree t;
int m = 1;
while (m != 0) {
cout << "Choose an option:" << endl << "1- To Add new clients." << endl << "2- To Display the clients." << endl << "3- To Store the clients in a Text Document." << endl << "4- To Search for a specific client through it's ID." << endl << "5- To Edit a specific client's information" << endl << "6- To Delete a specific client." <<endl<<"7- Exit."<< endl;
cin >> opt;
switch (opt) {
case 1:
int n;
cout << "Enter the amount of clients: ";
cin >> n;
INFO *arr;
arr = new INFO[n];
cout << "Enter the elements of the array: " << endl;
for (int i = 0; i < n; i++)
{
cout << "Client #" << i + 1 << endl << "-----------" << endl;
cout << "Enter the ID: ";
cin >> arr[i].id;
cout << "Enter the name of the client: ";
cin >> arr[i].name;
cout << "Enter the balance: ";
cin >> arr[i].balance;
cout << "Enter the phone number: ";
cin >> arr[i].phone;
t.insert(arr[i]);
}
break;
case 2:
t.print(t.root);
break;
case 3:
t.store(t.root);
cout << "Saved!" << endl << "in directory: C:/Users/Taiseer/Documents/Visual Studio 2015/Projects/ADS Project/ADS Project" << endl;
break;
case 4:
cout << endl;
int s;
cout << "What element do you want to search for? ";
cin >> s;
if (t.searchid(t.root, s) == false) {
cout << " Not here.... :( \n";
}
cout << endl;
break;
case 5:
char x;
cin >> x;
if (x == 'y' || x == 'Y') {
int id;
cout << "Enter the id you want to edit: ";
cin >> id;
t.edit(id);
}
else
return;
break;
case 6:
break;
case 7:
m = 0;
break;
default:
cout << "lol" << endl;
}
}
}
The problem is that Tree::SAD() returns the node that is being searched for by value. This means that in Tree::edit(), the following line:
Node p = SAD(q);
Gets a copy of the actual node. Anything changed in p is not changed in the actual Tree. At the end of edit(), you try to insert(p.data), but this does not do anything, because your implementation of insert() never overwrites already existing nodes.
One solution is to make SAD() return a pointer to the found node. This has the added benefit that you can return nullptr to signal the case where the searched for id does not exist. This can then be used in edit() to change the fields of the Node structure directly.

Array of Structures - Functions not pulling through data

I am studying BscCS so I am familiar with programming concepts, however I always seem to get stuck on structs and arrays of structs.
I am required to convert parallel arrays into an array of structs. I have done this, but for some reason the information is not getting sent to the functions properly and the program keeps crashing.
Could you help identify where I am going wrong of if there is something I am missing? I don't need exact code for answers, just some guidance. Here is the code:
#define SIZE 3
struct Employee {
string firstName[SIZE];
string lastName[SIZE];
int id[SIZE];
int hoursWorked[SIZE];
int payRate[SIZE];
int stat[SIZE];
};
//Functions
int menu();
void printReport(Employee & employees);
void search(Employee & employees);
void calculatePay(Employee & employees);
void orderByLastName(Employee & employees);
void orderByid(Employee & employees);
void printActive(Employee & employees);
void printInactive(Employee & employees);
//Display Main Menu
int menu()
{
int choice;
cout << "1. Print out Employee Report. " << endl;
cout << "2. Search Employee Records. " << endl;
cout << "3. Display the Report in Sorted order on Last Name or ID. << endl;
cout << "4. Calculate Pay. " << endl;
cout << "5. Display Active Employees." << endl;
cout << "6. Display Inactive Employees." << endl;
cout << "7. Quit" << endl;
cout << "Enter your choice. ";
cin >> choice;
return choice;
}
//Display the employee data in a formatted order
void printReport(Employee & employees)
{
cout << setw(10) << "First Name" <<
setw(10) << "Last Name" <<
setw(10) << "ID" <<
setw(10) << "Hours" <<
setw(10) << "Rate" <<
endl;
ios::fixed;
for (int index = 0; index < SIZE; index++)
cout << setw(10) << employees.firstName[index] <<
setw(10) << employees.lastName[index] <<
setw(10) << employees.id[index] <<
setw(10) << employees.hoursWorked[index] <<
setw(10) << employees.payRate[index] << endl;
}
//Search for employee ID
//Show "Not Found" if unable to locate
void search(Employee & employees)
{
bool found = false;
int idNumber;
int pos = -1;
cout << "Enter id number ";
cin >> idNumber;
for (int index = 0; index < SIZE && !found; index++)
{
if (employees.id[index] == idNumber)
{
found = true;
pos = index;
}
}
if (!found)
cout << "Not Found. " << endl;
else
cout << setw(10) << employees.firstName[pos] <<
setw(10) << employees.lastName[pos] <<
setw(10) << employees.id[pos] <<
setw(10) << employees.hoursWorked[pos] <<
setw(10) << employees.payRate[pos] << endl;
}
//Calculate total weekly pay
void calculatePay(Employee & employees)
{
cout << setw(10) << "First Name" <<
setw(10) << "Last Name" <<
setw(10) << "ID" <<
setw(10) << "Hours" <<
setw(10) << "Rate" <<
setw(10) << "Total Pay" <<
endl;
ios::fixed;
for (int index = 0; index < SIZE; index++)
cout << setw(10) << employees.firstName[index] <<
setw(10) << employees.lastName[index] <<
setw(10) << employees.id[index] <<
setw(10) << employees.hoursWorked[index] <<
setw(10) << employees.payRate[index] <<
setw(10) << employees.hoursWorked[index] * employees.payRate[index] << endl;
}
//Sort employee data by last name
void orderByLastName(Employee & employees)
{
for (int i = 0; i < SIZE; i++)
{
for (int j = 0; j < SIZE - 1; j++)
{
if (employees.lastName[j] > employees.lastName[j + 1])
{
string temp = employees.lastName[j];
employees.lastName[j] = employees.lastName[j + 1];
employees.lastName[j + 1] = temp;
temp = employees.firstName[j];
employees.firstName[j] = employees.firstName[j + 1];
employees.firstName[j + 1] = temp;
int tempid = employees.id[j];
employees.id[j] = employees.id[j + 1];
employees.id[j + 1] = tempid;
int temphours = employees.hoursWorked[j];
employees.hoursWorked[j] = employees.hoursWorked[j + 1];
employees.hoursWorked[j + 1] = temphours;
int temppayrate = employees.payRate[j];
employees.payRate[j] = employees.payRate[j + 1];
employees.payRate[j + 1] = temppayrate;
}
}
}
}
//Sort employee data by ID
void orderByid(Employee & employees)
{
for (int i = 0; i < SIZE; i++)
{
for (int j = 0; j < SIZE - 1; j++)
{
if (employees.id[j] > employees.id[j + 1])
{
string temp = employees.lastName[j];
employees.lastName[j] = employees.lastName[j + 1];
employees.lastName[j + 1] = temp;
temp = employees.firstName[j];
employees.firstName[j] = employees.firstName[j + 1];
employees.firstName[j + 1] = temp;
int tempid = employees.id[j];
employees.id[j] = employees.id[j + 1];
employees.id[j + 1] = tempid;
int temphours = employees.hoursWorked[j];
employees.hoursWorked[j] = employees.hoursWorked[j + 1];
employees.hoursWorked[j + 1] = temphours;
int temppayrate = employees.payRate[j];
employees.payRate[j] = employees.payRate[j + 1];
employees.payRate[j + 1] = temppayrate;
}
}
}
}
void printActive(Employee & employees)
{
bool found = false;
int pos = -1;
for (int index = 0; index < SIZE && !found; index++)
{
if (employees.stat[index] == 1)
{
found = true;
pos = index;
}
if (!found) {
cout << "No active employees." << endl;
}
else {
cout << setw(10) << employees.firstName[pos] <<
setw(10) << employees.lastName[pos] <<
setw(10) << employees.id[pos] <<
setw(10) << employees.hoursWorked[pos] <<
setw(10) << employees.payRate[pos] << endl;
}
}
}
void printInactive(Employee & employees)
{
bool found = false;
int pos = -1;
for (int index = 0; index < SIZE && !found; index++)
{
if (employees.stat[index] == 0)
{
found = true;
pos = index;
}
if (!found) {
cout << "No inactive employees." << endl;
}
else {
cout << setw(10) << employees.firstName[pos] <<
setw(10) << employees.lastName[pos] <<
setw(10) << employees.id[pos] <<
setw(10) << employees.hoursWorked[pos] <<
setw(10) << employees.payRate[pos] << endl;
}
}
}
int main()
{
struct Employee employees[SIZE];
//Read first and last name from user
for (int index = 0; index < SIZE; index++)
{
cout << "Enter first name : ";
cin >> employees[index].firstName[index];
cout << "Enter last name : ";
cin >> employees[index].lastName[index];
//Read ID, hours, and pay rate from user
while (employees[index].id[index] < 0)
{
cout << "Enter id : ";
cin >> employees[index].id[index];
if (employees[index].id[index] < 0)
{
cout << "Invalid Id number. " << endl;
cout << "Enter id : ";
cin >> employees[index].id[index];
}
}
while (employees[index].hoursWorked[index] < 0)
{
cout << "Enter hours worked : ";
cin >> employees[index].hoursWorked[index];
if (employees[index].hoursWorked[index] < 0)
{
cout << "Invalid hours. " << endl;
cout << "Enter hours worked : ";
cin >> employees[index].hoursWorked[index];
}
}
while (employees[index].payRate[index] < 0)
{
cout << "Enter Pay Rate : ";
cin >> employees[index].payRate[index];
if (employees[index].payRate[index] < 0)
{
cout << "Invalid pay rate. " << endl;
cout << "Enter Pay Rate : ";
cin >> employees[index].payRate[index];
}
}
while (employees[index].stat[index] < 0)
{
cout << "Enter your status. (0 - Inactive, 1 - Active) : ";
cin >> employees[index].stat[index];
if (employees[index].stat[index] < 0)
{
cout << "Enter your status : ";
cin >> employees[index].stat[index];
}
cout << endl;
}
}
//Loop to display menu options until user quits program
while (true)
{
//Call menu with options
int ch = menu();
//Different options to choose
switch (ch)
{
case 1:
printReport(employees[SIZE]);
break;
case 2:
search(employees[SIZE]);
break;
case 3:
int sortType;
cout << "1.Sort by Last Name." << endl;
cout << "2.Sort by ID." << endl;
cout << "Enter your choice. ";
cin >> sortType;
if (sortType == 1)
orderByLastName(employees[SIZE]);
else if (sortType ==2)
orderByid(employees[SIZE]);
break;
case 4:
calculatePay(employees[SIZE]);
break;
case 5: printActive(employees[SIZE]);
case 6: printInactive(employees[SIZE]);
break;
case 7:
exit(0);
}
}
system("pause");
return 0;
}
Thank you in advance!
I ran your program, and I received more than 20 errors before the compiler involuntarily stopped trying to compile any longer. All of them are connected to the lines of code using cout, cin, string, and setw. You need to use these keywords with the std namespace to fix this, and you need to include the iostream header file (#include <iostream>). Either you can write std:: in front of all of these keywords (i.e. std::cout) or you can declare the namespace in the preprocessor (using namespace std;). Also, for std::setw, you need to include the iomanip header file (#include <iomanip>). After that, you're missing a quotation in the menu function and a bracket at the end of the main function. (There's also a couple of problems with initializing the size of the struct members in the declaration, but I'll leave that up to you.) Hope this helped!