How to get values from array of const char?

Hello i'm making a program witch calculates age gap of humans.
I need to pass name and birthday to my Human class and i can't figure out how.
Here is my code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>

using namespace std;

class Human{
public:
    string * name;
    int * birth;
    Human(string * s, int * i) : name(s), birth(i){}; //Constructor passing address of name and birthday values.
};

int main()
{
    const char buff[] = "Tom 1993 \n Jim 1983";

    Human human1(/*Need to pass pointer to Tom*/, /*Need to pass pointer to 1993*/);
    Human human2(/*Need to pass pointer to Jim*/, /*Need to pass pointer to 1983*/);

    cout << (*human1.name) <<" and "<< (*human2.name) <<" age gap is: "<< (*human1.birth) - (*human2.birth) << endl;

    return 0;
}


The output should be: Tom and Jim age gap is: 10

Thank you for reading.
Why the pointers in that class? Why not just use "normal" non-pointer instances?

By the way if you insist on using those horrible pointers, where are you allocating memory for them?

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
#include <iostream>
#include <sstream>
#include <string>
using namespace std;

class Human {
public:
    string  name;
    int     birth;
    Human(string s, int i) : name(s), birth(i) {};
};

int main() {
    const char buff[] = "Tom 1993 \n Jim 1983";

    istringstream sin(buff);
    string name;
    int year;

    sin >> name >> year;
    Human human1(name, year);

    sin >> name >> year;
    Human human2(name, year);

    cout << human1.name <<" and "<< human2.name <<" age gap is: "
         << human1.birth - human2.birth << endl;
}

jib i already have allocated the values for name and bithday inside buff if i use pointers i don't need to allocate unnecessary space.

tpb i want to use pointers inside Class Human.
i already have allocated the values for name and bithday inside buff if i use pointers i don't need to allocate unnecessary space.

Do you not realize that a std::string is not the same as a const char*?

want to use pointers inside Class Human.

Why? Using pointers in C++ should be a last resort.



jib can i use:
 
const char * name[9];

instead of string?
Why? Where are you going to allocate memory for that pointer?

from const char buff[] = "Tom 1993 \n Jim 1983";

and i think that my human class need to look this :
1
2
3
4
5
class Human{
public:
    const char * name[9];
    const int * birth;
    Human(const char * s[9], const int * i) : name(s), birth(i){};

Last edited on
Still where are you allocating memory for those pointers? The code you posted is not allocating memory for those pointers.
Topic archived. No new replies allowed.