Display

I am trying to output the result but it doesn't show anything.
In my header file i have this
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
struct info
{
  char * name;
  int age;
};
class player
{
  public:
   player();
   void read();
   void display():
  private:
   info * memb;
   int num;
};


In my implement file
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
player::player()
{
num = 0;}
void player::read(){
 char * name = new char[20];
 cout << "Enter a Name: ";
 cin.get (name, 20, '\n')

 int age;
 cout << "Enter age: ";
 cin >> age;
}
void player::display()
{for ( int a= 0; a<num; ++a)
cout << memb[a].name <<memb[a].age;
}

In main file
1
2
3
4
5
6
7
int main()
{
 player info;
 info.display();
 
 return 0;
}
Last edited on
You sent num equal to 0 in the constructor, then your for loop in the display function runs as long as 0 is less than num.

So in this case it will never run.
i changed the num = 5 in constructor but still not displaying.
if i understand your code correctly, it should equal the number of elements in info, in which case it should be 2
Here is the modified code i wish it will help you
modify the code that prints out i made it just 2 counts for example...

here is the header;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#ifndef Player_H
#define Player_H

struct info
{
  char * name;
  int age;
  info();
};
class player
{
  public:
   player();
   void read(int a);
   void display();
  private:
   info* memb;
};

#endif Player_H


and the implement

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

#include <iostream>
#include "player.h"

using namespace std;

info::info() {
	name = new char[20];
	age = 0;
}

player::player()
{
memb = new info[20];
}
void player::read(int a) {
 cout << "Enter a Name: ";
 cin >> memb[a].name;
 cout << "Enter age: ";
 cin >> memb[a].age;
 cout << endl;
}
void player::display()
{for ( int i= 0; i<2; ++i){
cout << memb[i].name << " " << memb[i].age;
cout << endl;
}
}


and the main

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include "player.h"

using namespace std;
int main()
{
 player info;
 for(int i=0; i<2; i++) info.read(i);
 info.display();
 system("pause");
 return 0;

}
Well, the function player::read() does nothing but wasting memory. It should be a member function of struct info.

in class player you have to new (and later in the destructor delete) the array memb according to num and then you can display the whole thing. Either num is fixed or you provide the amount as a parameter to the constructor
Thanks all for the reply. I was able to display successfully. Instead of entering info. just 2 times can i use loop until user is satisfied entering info.
Topic archived. No new replies allowed.