Values to heap question

Pages: 12
Global variables are not a good idea in general.
A better alternative is to have local variables in your main
and pass them to the functions you want by (const) reference.

A struct could be used to hold the player info.
Structs is a way you can build your own types
out of other types (primitive or user defined).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include <iostream>
#include <string>
using namespace std;

struct Player
{
    string name;
    int hp;
    int money;
    int strength;
    int power;
    int speed;
};

struct Monster
{
    string name;
    int hp;
    int damage;
};

void Print(const Player & p)
{
    cout << "name: " << p.name << endl;
    cout << "money: " << p.money << endl;
    cout << "strength: " << p.strength << endl;
    cout << "power: " << p.power << endl;
    cout << "speed: " << p.speed << endl;
}

void Battle(Player & p, Monster & m)
{
    cout << p.name << " fights against " << m.name << endl;
}

int main()
{
    Player hero;

    cout << "enter your name: ";
    getline(cin,hero.name);

    hero.money=1000;
    hero.hp=150;
    hero.strength=20;
    hero.power=15;
    hero.speed=10;

    Print(hero);

    Monster bad_guy;

    bad_guy.name="zergling";
    bad_guy.hp=35;
    bad_guy.damage=5;

    Battle(hero,bad_guy);

    cout << "\n(hit enter to quit...)" << endl;
    cin.get();

    return 0;
}

Faurax wrote:
Is there a similar way to use an integer instead of string in this case? getline(infile, stringName);

If you don't care about input validation, you can just do -> infile >> moneycurrent;

Useful links:

http://cplusplus.com/doc/tutorial/
http://cplusplus.com/doc/tutorial/functions2/
http://cplusplus.com/doc/tutorial/structures/
Last edited on
Does anyone here know where to look for a tutorial on opening a .txt file for an example,
using the value of a string as the name for the file to open?

Example:
1
2
3
4
5
6
String FileName;
FileName = "Save1.txt";
       ifstream infile;
           infile.open("");
           ...
           infile.close();

Instead of writing a file name in "" , I want it to open a file that has the
same name as the value of the string "FileName". By importing the value
from the string as name of the file to open.
Last edited on
1
2
3
4
5
string filename;
getline(cin,filename);

ifstream infile;
infile.open(filename.c_str());

http://cplusplus.com/reference/string/string/c_str/
Once again, thanks!
Topic archived. No new replies allowed.
Pages: 12