0

I am trying to create a program that asks a user how many babies they have, gather input about each baby, and then displays it on the console. I am 90% of the way there but I am stuck.

The input/output on the console should look like this;

Please enter the number of babies: 2

Please enter baby #1's height : 21.5

Please enter baby #2's height : 19.75

Baby #1's info: Height: 21.5 inches

Baby #2's info: Height: 19.75 inches

The output for my code keeps showing 19.75 as the height for both babies. I realize I probably need to use a pointer to dynamically allocate different values to aBaby.height, but I haven't used a pointer within a structure before. Any help would be greatly appreciated.

#include <iostream>
using namespace std;

struct Baby {
double length;
};
int main ()
{    
int iNumBaby = 0;

cout<<"Please enter the number of babies: ";
cin>>iNumBaby;
cout<<endl;
Baby aBaby;

Baby* pBaby = new Baby[iNumBaby];

for(int i = 0; i < iNumBaby; i++)
{
cout << "Please enter baby #"<< i + 1 <<"'s height <inches>: ";
cin >> aBaby.length;
cout << "\n";
}  
for(int i = 0; i < iNumBaby; i++)
{
cout << "\Baby #"<<i + 1<<"'s info:\n";
cout << "Height: " <<aBaby.length<<" inches"<<endl;
cout << "\n";
}
system("PAUSE");  
delete[] pBaby;
return 0;
}
Mike U
  • 79
  • 2
  • 9

2 Answers2

1

It's nothing to do with pointers, you simply have a bug in your code. See the following block:

for(int i = 0; i < iNumBaby; i++)
{
    cout << "Please enter baby #"<< i + 1 <<"'s height <inches>: ";
    cin >> aBaby.length;
    cout << "\n";
}

The main problem here is that you are storing the entry into aBaby.length every time. In fact, you never used pBaby anywhere in your code. I assume this is what you want:

for(int i = 0; i < iNumBaby; i++)
{
    cout << "Please enter baby #" << i + 1 << "'s height <inches>: ";
    cin  >> pBaby[i].length;
    cout << "\n";
}

for(int i = 0; i < iNumBaby; i++)
{
    cout << "Baby #" << i + 1 <<"'s info:\n";
    cout << "Height: " << pBaby[i].length << " inches" << endl;
    cout << "\n";
}
  • Thank you both. It was indeed a syntax error, I'm pretty new at this. Had to change to cin >> pBaby[i].length; and cout << pBaby[i].length. – Mike U Mar 07 '13 at 05:59
1
for(int i = 0; i < iNumBaby; i++)
{
cout << "Please enter baby #"<< i + 1 <<"'s height <inches>: ";
cin >> aBaby.length;
cout << "\n";
}  

the problem lies in your assignment to aBaby.length. You are assigning every baby's length to the same object. Try accessing the array of babies that you created and change the length of those. Example:

cin >> pBaby[i].length
WhiteboardDev
  • 819
  • 7
  • 10