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";
}
}
Related
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 :)
So I want to search my array for my data and move back and forth, so this is what i came up with, however this isn't working, can there be a better way to do this ? I tried to google some tips however I wasn't finding a suitable way to do this...
Can binary search be used to do this same thing ?
struct student
{
int stid = NULL;
char stname[15] = "NULL";
int grades = NULL;
string date = NULL;
};
int main()
{
int choose = 0;
int stid = 0;
int array = 1;
struct student s[1] = { 001, "Sara", "123456", "Canada", "02/01/2019" };
while (choose != 4)
{
cout << "1. Add\n";
cout << "2. View\n";
cout << "3. Search\n";
cout << "4. Quit\n";
cin >> choose;
if (choose == 3)
{
cout << "How would you like to find the Student Details?" << endl;
cout << "1 - By student id " << endl;
int choice = 0;
cin >> choice;
if (choice == 1)
{
cout << "Student ID: ";
cin >> stid;
for (int i = 0; i < array; i++)
{
if (s[i].stid == stid)
{
cout << "ID: " << s[i].stid << "\n";
cout << "Name: " << s[i].stname << "\n";
cout << "Grades: " << s[i].grades << "\n";
cout << "Date joined school: " << s[i].date<< "\n";
while (true)
{
cout << "Which record do you wish to see?" << endl;
cout << " 1 : Forth " << endl;
cout << " 2 : Back " << endl;
int choice = 0;
cin >> choice;
if (choice == 1)
{
stid = stid + 1;
for (int i = 0; i == stid; i++)
{
if (s[i].stid == stid)
{
cout << "ID: " << s[i].stid << "\n";
cout << "Name: " << s[i].stname << "\n";
cout << "Grades: " << s[i].grades << "\n";
cout << "Date joined school: " << s[i].date<< "\n";
}
}
}
else if (choice == 2)
{
stid = stid - 1;
for (int i = 0; i == stid; i++)
{
if (s[i].stid == stid)
{
cout << "ID: " << s[i].stid << "\n";
cout << "Name: " << s[i].stname << "\n";
cout << "Grades: " << s[i].grades << "\n";
cout << "Date joined school: " << s[i].date<< "\n";
}
}
}
Thank you for helping.
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();
}
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.
Very new to programming.
This bit of my program accepts two strand of DNA as input and output them in a double helix drawing. The problem is, if one of the two input strand is longer than the other, i will receive error.
So I thought, is it possible that if strand[add] is non-existent anymore, replace it with *?
#include <iostream>
#include <string>
#include <conio.h>
using namespace std;
void helix(string &strand1, string &strand2)
{
int nucleo;
int length;
if (strand1.length() >= strand2.length())
{
length = strand1.length();
}
else
{
length = strand2.length();
}
int add;
for (int add = 0; add <= length - 1; add++)
{
if (add > 7)
{
nucleo = add % 8;
}
else
{
nucleo = add;
}
if (nucleo == 0)
{
cout << " " << strand1[add] << "---"<<strand2[add] << endl;
}
else if (nucleo == 1)
{
cout << " " << strand1[add] << "------" << strand2[add] << endl;
}
else if (nucleo == 2)
{
cout << " " << strand1[add] << "------" << strand2[add] << endl;
}
else if (nucleo == 3)
{
cout << " " << strand1[add] << "---" << strand2[add] << endl;
cout << " *" << endl;
}
else if (nucleo == 4)
{
cout << " " << strand2[add]<<"---" << strand1[add] << endl;
}
else if (nucleo == 5)
{
cout << " " << strand2[add]<<"------" << strand1[add] << endl;
}
else if (nucleo == 6)
{
cout << " " << strand2[add]<<"------" << strand1[add] << endl;
}
else if (nucleo == 7)
{
cout << " " << strand2[add]<<"-----" << strand1[add] << endl;
cout << " *" << endl;
}
}
}
int main()
{
string strand1,strand2;
cout << "ENTER STRAND:" << endl;
cin >> strand1;
cout << "ENTER STRAND:" << endl;
cin >> strand2;
helix(strand1,strand2);
_getch();
return 0;
}
I was hoping I could still show the longer strand even if the other side of the strand is empty(want to put *) like this :imgur.com/t7riVrS
I think you inverted the legnth test, it should be:
//if (strand1.length() >= strand2.length())
if (strand1.length() < strand2.length())
{
length = strand1.length();
}
else
{
length = strand2.length();
}
Edit:
If you want it fill one the string with '*', replace the code above with:
while (strand1.length() < strand2.length())
{
strand1 += "*";
}
while (strand1.length() > strand2.length())
{
strand2 += "*";
}