getline issue

Hello everyone,

Let start by saying thanks in advance for you help. Here is my code:
_______________________________________________________________________________
#include <iostream>
#include <string>

using namespace std;

struct Car
{
string Make;
int Year;
};

int main()
{
int NumCars = 0;

cout << "How many cars do you wish to catalog?";
cin >> NumCars;

Car * Catalog = new Car[NumCars];

for(int index = 0; index < NumCars; ++index)
{
cout << "Car #" << index + 1 << endl;
cout << "Enter the make: ";
getline(cin, Catalog[index].Make);
cout << "Enter the year it was built: ";
cin >> Catalog[index].Year;
}

cout << "You have entered " << NumCars << " cars, here are the cars:" << endl;

for (int index = 0; index < NumCars; ++index)
{
cout << "Car #" << index +1 << endl;
cout << Catalog[index].Make << endl;
cout << Catalog[index].Year << endl;
}

return 0;
}


Now, what should happen is you are prompted to enter the name and year of a number of cars adn the program spits them back out from an array of structures. What actually happend is that the string input for the make is skipped entirely. Can someone please tell me why?
You are mixing >> and getline, you shouldn't do this. Read http://www.cplusplus.com/forum/articles/6046/

And please use [code][/code] tags
...your close...notice all I did was added the cin.ignore() in lines 18 and 29. When you mix cin and the getline, you need a cin.ignore after the cin to clear the buffer (I think)...

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
#include <iostream>
#include <string>

using namespace std;

struct Car
{
string Make;
int Year;
};

int main()
{
int NumCars = 0;

cout << "How many cars do you wish to catalog?";
cin >> NumCars;
cin.ignore();

Car * Catalog = new Car[NumCars];

for(int index = 0; index < NumCars; ++index)
{
cout << "Car #" << index + 1 << endl;
cout << "Enter the make: ";
getline(cin, Catalog[index].Make);
cout << "Enter the year it was built: ";
cin >> Catalog[index].Year;
cin.ignore();
}

cout << "You have entered " << NumCars << " cars, here are the cars:" << endl;

for (int index = 0; index < NumCars; ++index)
{
cout << "Car #" << index +1 << endl;
cout << Catalog[index].Make << endl;
cout << Catalog[index].Year << endl;
}

return 0;
}
OK, that works and now I understand why but now I have a new question. If it is a bad idea to mix >> and getline, how would I write this program using only getline? I tried it and got several pages of errors.
Topic archived. No new replies allowed.