loops and classes
I can easily hard code the required data, but I am having trouble using a loop to enter the data into the class.
Currently the program is skipping the first name, and outputting missing the first character of the name. How would I rectify this?
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
|
////Task 2: Band
#include <iostream>
#include "Member.h"
using namespace std;
int main()
{
int size = 0;
cout << "Enter the amount of members of the band: ";
cin >> size;
Member* band = new Member[size];
for (int i = 0; i < size; i++)
{
string x;
cout << "Enter name: ";
getline(cin, x);
cin.ignore();
band[i].stageName(x);
}
for (int j = 0; j < size; j++)
{
cout << endl << band[j].getStageName() << endl;
}
system("PAUSE");
return 0;
}
|
//Member Class
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 "Member.h"
Member::Member()
{
}
Member::~Member()
{
}
void Member::stageName(string x)
{
name = x;
}
void Member::instrument(string y)
{
instrum = y;
}
string Member::getStageName()
{
return name;
}
string Member::getInstrument()
{
return instrum;
}
|
Last edited on
You need to move line 19 to line 10, then it works. At the end of main you should delete your pointer.
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
|
int main()
{
int size = 0;
cout << "Enter the amount of members of the band: ";
cin >> size;
cin.ignore();
Member* band = new Member[size];
for (int i = 0; i < size; i++)
{
string x;
cout << "Enter name: ";
getline(cin, x);
band[i].stageName(x);
}
for (int j = 0; j < size; j++)
{
cout << endl << band[j].getStageName() << endl;
}
delete [] band;
system("PAUSE");
return 0;
}
|
OUTPUT:
Enter the amount of members of the band: 3
Enter name: Tim
Enter name: Tom
Enter name: Anna
Tim
Tom
Anna
|
Thank you, I feel so silly. cin.ignore() should always come after the cin?
Topic archived. No new replies allowed.