Getline for pointers in a structure problem

Hello, right now I am working on a problem in a programming book that I have and for some reason I cannot use getline to gather a line of text.

I had everything correct except it needs to be able to take it a line of text.

I currently have:

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

struct cars
{
       string make;
       int year;
};

int main()
{
    cout << "How many cars do you want to add?" << endl;
    int howMany;
    cin >> howMany;
    int carNumber = 1;
    
    cars * car = new cars[howMany];
    
    for(int y = 0; y < howMany; y++)
    {    
       cout << "\nCar #" << carNumber << endl;
       cout << "\nPlease enter the make: " << endl;
       getline(cin, car[y].make);        //cin >> car[y].make; - 1 word
       
       cout << "Please enter the year made: " << endl;
       cin >> car[y].year;
       cout << "\n" << endl;
       carNumber++;
    }
    
    cout << "Here is your collection: " << endl;
    
    for(int z = 0; z < howMany; z++)
    {
       cout << car[z].year << " " << car[z].make << endl;
    }
    
    cin.get();
    cin.get();
    return 0;
}


I do not have any error codes or anything, but when I launch the program it skips the "Please enter a year made" question as if there was already a blank value stored in the system for it.

I have used the getline function before but for some reason there is a problem
with me trying to use it to point to a a new structure value.
Any helpful advice is welcome, thanks!
cin >> howMany;

This will leave an extra '\n' in the buffer, you'll need to remove it.

Btw, your program has a memory leak, you aren't ever deleteing the array you make.
Last edited on
Hm strange, why exactly does it leave an extra '\n' in the buffer?
Because it is the formatted input operator. It stops at whitespace characters, and '\n' is one of them.
Ah ok, thanks for the help.
Topic archived. No new replies allowed.