Understanding Data Structures and Classes C++ - c++

So I'm having trouble understanding how Struct works in C++ I have develop a code in which I've been playing for a while but I don't seem to display for the results I'm looking for. I don't get any compiler errors or mistakes so it seems to be running ,This is what I have ...
Question: How do I display the results in "void Save_Player_Name(Player_Data Player)" later on in the future... ?
struct Player_Data
{
public: string Player_Name;// name of the player will be store here
}Customer[1];
int main()
{
Save_Name_File();
}
void Save_Name_File()// will capture the name of the player
{
int n;
int i = 1;// number of players
//cin.get();
for (n=0; n<i; n++)// will the player
{
cout << string(30, '\n');
cout << "Player Amount " << n << " Out of : " << i;
cout << "\n Please enter the name you wish to play \n\n Name: ";
getline (cin,Customer[n].Player_Name);
}
}
void Save_Player_Name(Player_Data Player)// will store the name of the player in a file
{
ofstream scores_data;
scores_data.open ("scores.dat", std::ios_base::app);
cout << Player.Player_Name << endl;
scores_data<< Player.Player_Name << "\n";
scores_data.close();
}

Edit: minor fixes.
Edit: Added class consideration.
Question: How do I display the results in "void
Save_Player_Name(Player_Data Player)" later on in the future... ?
If you are asking how to read the data in from a file:
const bool readFile()
{
ifstream ip;
ip.open("scores.dat", ifstream::in);
if( !ip )
{
printf("Unable to open file.");
return false;
}
// loop over every line in the file
string bffr;
while( getline(ip, bffr) )
{
<do something>
}
}
If you are referring to how to access the data stored in the variable:
Technically, you should be able to do the following from main:
Save_NameFile();
printf("Player name: %s", Customer[n].Player_name.c_str());
However, having Customer be global is bad for a number of reasons. Instead, you should create a local instance in main and pass it to your functions. You will then be able to access it in the same manner.
Note: I used printf instead of cout. I would recommend getting familiar with it. You'll need to include stdio.h, I believe.
Also, you need to make sure you are passing your struct by reference. There are a number of reasons why you should do this, but you will need to in order to get the data back out.
void Save_Player_Name(Player_Data &Player) {<<stuff here>>}
You should also be declaring your functions before main:
struct Player_Data
{
public: string Player_Name;// name of the player will be store here
};
void askUserForName(Player_Data &);
void writeNameToFile(Player_Data &);
void main()
{
Player_Data player;
askUserForName(player);
return;
}
void askUserForName(Player_Data &player)
{
<<do stuff>>
writeNameToFile(player);
return;
}
etc.
Unless you really need to use a struct, I would recommend going with classes. Structs make everything (variables and methods) public by default, whereas classes are private by default. In reality, structs and classes are identical--you can use them fairly interchangeably (don't shoot me!); in practice, structs are generally used when you need to aggregate some data (i.e., variables) without methods.
Your class might end up something like this (I haven't tested it, and I've been coding in Python lately, so please forgive any minor errors):
class PlayerData
{
public:
PlayerData()
{
}
~PlayerData()
{
}
void askUserForName()
{
<<code here>>
}
void writeNameToFile()
{
<<code here>>
// also write to screen
printf("[Write to console] name: %s\n", this->name_.c_str());
}
private:
std::string name_;
};
void main()
{
PlayerData player;
player.askUserForName();
player.writeNametoFile();
return;
}
In reality, you'd want to use a header file and separate things out, but I'll leave that for another day.

You haven't called the method that saves the player after you call Save_Name_File()
You need some logic fixes for your code
#include <iostream>
#include <fstream>
using namespace std;
struct Player_Data
{
public: string Player_Name;// name of the player will be store here
}Customer[1];
void Save_Player_Name(Player_Data Player)// will store the name of the player in a file
{
ofstream scores_data;
scores_data.open ("scores.dat", std::ios_base::app);
cout << Player.Player_Name << endl;
scores_data<< Player.Player_Name << "\n";
scores_data.close();
}
void Save_Name_File()// will capture the name of the player
{
int n;
int i = 1;// number of players
//cin.get();
for (n=0; n<i; n++)// will the player
{
cout << "Player Amount " << n << " Out of : " << i;
cout << "\n Please enter the name you wish to play \n\n Name: ";
getline (cin,Customer[n].Player_Name);
Save_Player_Name(Customer[n]);
}
}
int main()
{
Save_Name_File();
return 0;
}

Related

How to execute a class method by string input in C++

I am trying to develop a text adventure in C++ where users can input string commands (ex. "take apple").
Here is a very naive sample of code I came up with:
# include <iostream>
using namespace std;
class fruit{
public:
string actual_name;
fruit(string name){
actual_name = name;
}
take() {
cout << "You take a " << actual_name << "." << endl;
}
};
fruit returnObjectFromName(string name, fruit Fruits[]){
for(int i = 0; i <= 1; i++){ // to be modified in future depending on Fruits[] in main()
if (Fruits[i].actual_name == name)
return Fruits[i];
}
}
int main(){
string verb;
cout << "Enter verb: ";
cin >> verb;
string object;
cout << "Enter object: ";
cin >> object;
fruit apple("apple");
fruit Fruits[] = { apple }; // to be extended in future
// returnObjectFromName(object, Fruits). ??? ()
}
How can I possibly get the fruit method with something similar to the function returnObjectFromName, if this is even possible?
I began the development with Python (independently), and there I can at least use eval(), but as I understand in C++ this is not an option.
I tried also with map, but I didn't manage to make it work with methods.
Thank you all for your answers.
Its not good way to rely on reflection in C++ and i think there is no way to list methods in classes. Maybe you can use function pointers but pointer to instance methods are hell.
I recommend to use polymorphism and good design. If some items might be taken, then use interface like this:
#include <iostream>
using namespace std;
class ITakeable {
public:
virtual bool isTakeable() = 0;
virtual void take() = 0;
virtual void cannotTake() = 0;
};
class fruit : public ITakeable {
public:
string actual_name;
fruit(string name){
actual_name = name;
}
bool isTakeable() {
return true;
}
void take() {
cout << "You take a " << actual_name << "." << endl;
}
void cannotTake() {
cout << "not needed to be implemented";
}
};
class airplane : public ITakeable {
public:
string actual_name;
airplane(string name){
actual_name = name;
}
bool isTakeable() {
return false;
}
void take() {
cout << "not needed to be implemented";
}
void cannotTake() {
cout << "You CANNOT take a " << actual_name << "." << endl;
}
};
int main() {
fruit apple("apple");
if (apple.isTakeable()) {
apple.take();
}
airplane plane("boeing");
if (plane.isTakeable()) {
plane.take();
} else {
plane.cannotTake();
}
// use of interface in general
ITakeable * something = &apple;
if (something->isTakeable()) {
something->take();
}
something = &plane;
if (something->isTakeable()) {
something->take();
} else {
something->cannotTake();
}
return 0;
}
Since fruit is a user defined type, you have to declare your own methods for your type or you inherit from one previously defined.
There are a lot of method for "built-in" string type
that Performs virtually the same job as eval (...) in python.
Also I noticed your function need not be defined independently outside of class fruit.

How do I read a .txt file with an undefined number of values using an array (C++)?

I am entirely new to programming so I'm sorry if I don't explain this well. For my C++ assignment I had to write an object-oriented program that reads the names from a text file (the text file is just a list of first names) and prints them to the console in alphabetical order using an array. Originally, the description of the assignment said that the file had 20 names, so I based my code around that. The program works, but now it turns out the assignment description was inaccurate and we shouldn't assume that the text file has a specific number of names. How do I convert my code from specifically reading 20 names to instead reading an undefined number of names, while still using an array?
I don't fully understand the concepts that I'm implementing so it's difficult for me to know how to change my code while still following the requirements of the assignment. Here is my code:
#include <iostream>
#include <algorithm>
#include <fstream>
#include <string>
using namespace std;
class Names
{
private:
ifstream inStudents;
string studentNames[20];
string name;
int j;
public:
Names();
~Names();
void openFile(string);
void testFile();
void readFile();
void sortNames();
void closeFile();
void display();
};
Names::Names()
{
}
Names::~Names()
{
}
void Names::openFile(string d)
{
inStudents.open(d);
}
void Names::testFile()
{
if (!inStudents)
{
cout << "File did not open" << endl;
exit(10);
}
}
void Names::readFile()
{
cout << "Reading the input file..." << endl;
int j = 0;
while (inStudents >> name && j < 20)
{
studentNames[j++] = name;
}
}
void Names::sortNames()
{
sort(studentNames, studentNames + 20);
}
void Names::closeFile()
{
inStudents.close();
}
void Names::display()
{
cout << endl << "The alphabetical list: " << endl << endl;
for (int i = 0; i<20; i++)
cout << studentNames[i] << " " << endl;
cout << endl << endl;
}
int main()
{
Names r;
r.openFile("students.txt");
r.readFile();
r.testFile();
r.sortNames();
r.display();
r.closeFile();
return 0;
}
You can use std::vector object instead of a regular array. It will look like that:
vector<string> studentNames;
Now, instead of using the following line to insert a name to a known place in the array:
studentNames[j++] = name;
use:
studentNames.push_back(name);
//or
studentNames.emplace_back(name);
The the while loop inside your readFile function, will look like this:
while (inStudents >> name)
{
studentNames.push_back(name);
}
To display it now, all you have to change in your display function is the range. The vector object include a function named size which returns you the current vector size, or in other words- the elements' count that the vector includes. It will seem like the following line:
for (int i = 0; i < studentNames.size(); i++)

In C++, how do I ask the user to input a string, have that string stored, and be able to recall it in any/many functions?

I want to be able to have the user enter their name, store it and be able to recall it in different functions. This is my first code, first program. I am sure there is an easier way to do this, so if you could offer both an answer to the question and a easier way of accomplishing this task it would be much appreciated. Thank you in advance.
This is what I have so far:
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>
#include <sstream>
using namespace std;
void game();
void other();
class NameClass{
public:
string name;
};
int main()
{
int a;
int age;
string name;
cout << "Hello user, what is you name? \n\n";
/*Not sure if class and operator needs to be here. I was hoping that when the user
input the stream(their name) it would be stored in the class as well as being able
to use it in the main function.*/
NameClass person;
//This line is here to get name from user.
getline(cin, name);
cout << "Well " << name << ", are you having a good day? \n\n";
cout << "1=Yes 2=No \n\n";
cin >> a;
cout <<"\n";
if(a==1){
cout << "Well that is good to hear.\n\n";
}else{
cout << "I am sorry to hear that. I hope things get better for you. \n\n";
}
cout << "Do you want to play a game? \n\n";
cin >> a;
if(a==1){
game();
}else{
other();
return 0;
}
return 0;
}
void game(){
/*It is in this function that I want the be able to recall the name that the user input in the main function.*/
cout << "Cool "<< name <<",let get started." << endl;
}
void other(){
cout << "Well then "<< name <<", lets do something else.";
}
I assume you aren't aware of the OOP concepts.
Do this (make methods part of the class):
class NameClass{
public:
string name;
void game();
void other();
};
int main()
{
...
NameClass person;
getline(cin, person.name);
...
}
Or this (pass name as parameter):
int main()
{
string name;
...
game(name);
}
void game(string name)
{
cout << "Cool "<< name <<",let get started." << endl;
}
If you want to pass information from one function to another then you use a function parameter (or more than one).
void game(string name);
int main()
{
string name;
...
game(name);
}
void game(string name)
{
cout << "Cool "<< name <<",let get started." << endl;
}
It's a fundamental concept that pretty much all programming languages have.
Just pass the name as a parameter in both your functions, it should be something like this:
//functions
void game(string name);
void other(string name);
In your main function when you call either function just pass the name to it.
if(a == 1)
{
game(name);
}
else
{
other(name);
}

Accessing variables from one class file in another one

I have the following files:
main.cpp
shop.hpp
player.hpp
With the following code in each of them:
main.ccp:
#include <iostream>
#include <cstdlib>
#include "shop.hpp"
using namespace std;
string *inventory= new string[3];
int invGold= 355;
int main(void){
shop store;
store.store();
}
shop.hpp:
#include <iostream>
#include <cstdlib>
using namespace std;
class shop{
public:
string shopOption;
string shopOptions[6]= {"Buy", "buy", "Sell", "sell", "Leave", "leave"};
string shopInv[3]= {"Sword", "Potion", "Arrows x 25"};
int shopInvAmount= sizeof(shopInv)/sizeof(shopInv[0]);
int shopPrices[3]= {250, 55, 70};
shop(){
cout << "Shopkeeper: We buy, we sell, what's your buisness?" << endl;
}
void store(void){
getline(cin,shopOption);
if(shopOption.compare(shopOptions[0]) == 0 || shopOption.compare(shopOptions[1]) == 0){
buy();
}
else if(shopOption.compare(shopOptions[2]) == 0 || shopOption.compare(shopOptions[3]) == 0){
sell();
}
else if(shopOption.compare(shopOptions[4]) == 0 || shopOption.compare(shopOptions[5]) == 0){
leave();
}
}
void buy(){
srand(time(0));
string buyQuotes[3]= {"What are you buyin', hon?", "Make it quick, I ain't got all day.", "Another day, another sell."};
int quotePick= rand() % sizeof(buyQuotes)/sizeof(buyQuotes[0]) - 1;
if (quotePick < 0){
quotePick= 0;
}
else if (quotePick > (sizeof(buyQuotes)/sizeof(buyQuotes))){
quotePick= sizeof(buyQuotes)/sizeof(buyQuotes);
}
cout << "TEST:" << sizeof(shopInv)/sizeof(shopInv[0]) << endl;
cout << buyQuotes[quotePick] << endl;
cout << "SHOP INVENTORY" << endl << "--------------" << endl;
cout << endl;
for (int i=0; i < sizeof(shopInv)/sizeof(shopInv[0]); i++){
cout << shopInv[i]<< ": " << shopPrices[i] << endl;
}
cout << endl << "What'll it be?:";
getline(cin,shopOption);
}
void sell(){
}
void leave(){
}
};
and player.hpp
class player{
public:
int playerHP= 18;
string playerInv[5] {};
int playerGold= 355;
};
Now, what i'd like to do, is that after the character selects the items they want to buy, and te amount of it, (Not programmed yet) check the price of the combined items, and see if the character has enough money on hand, and if the character buys the items, add them to the player's inventory.
But i'd like to keep the values the store uses, and everything related to the player in different class files.
Thing is, I have no idea how to pull something like that.
So, is t possible to access a class' variable from another class that is in another file althogether?
And if isn't, how would you suggest i get around this problem?
Start reading here: How does the compilation/linking process work? to get multiple files working for you. Odds are pretty good that whatever coding environment you are using will automate the process for you.
Then consider making an item class
class Item
{
public:
Item(string name, int price): mName(name), mPrice(price)
{
}
string getName()
{
return mName;
}
string getPrice()
{
return mPrice;
}
// other functions
private:
string mName;
int mPrice;
// other stuff
}
In Shop and Player, keep a list of Items
vector<Item> items;
When a Player tries to buy an item, find it in the list, ensure the Player can afford it, remove it from the Shop's list and add it to the Player's list.

How do I use the same string in 2 code blocks?

just start C++ through a series of youtube tutorials, I tried to look online but I did not know what vocabulary to use to explain my problem. I was testing pointers and I made this file which basically gets a username from the user and says it again but I don't know how reuse the username in another codeblock.
// Testing Pointerds.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
// This program just takes someones username and says it again.
// I get the name in void intro(), but how do I use the same string in another code block function?
// If I need to use it in 'void reuse()' how do I use the same name they type in in 'void intro()'?
void start()
{
cout << "What would you like to be called?"<<endl;
}
void usernameGet(string *a)
{
getline(cin,*a);
}
void intro()
{
string username;
start();
usernameGet(&username);
cout << "Welcome " << username << endl; // it has the username here but I want to use it in the next code block
cin.get();
}
void reuse()
{
// how do I use the same name in intro in this one?
}
int main()
{
intro();
reuse();
}
By passing the variable around, i.e. return it from the place where it's first initialized and pass it as an argument to the next place where it's needed. That way you avoid global state, which is nice.
You have to pass or return the value, something like:
std::string intro()
{
std::string username;
start();
usernameGet(&username);
std::cout << "Welcome " << username << std::endl;
std::cin.get();
return username;
}
void reuse(const std::string& name)
{
// Reuse name
}
int main()
{
std::string username = intro();
reuse(username);
}