Hey there! I'm new to c++ and programming in general and have a quick question to why the program below works. I had most of it completed but for hours i couldn't figure out why every time i tried to enter input for the "make" member of my dynamic structure array it would just skip over it in the program. I added the cin.get();
right before the getline(cin, carArray[i].make);
and all of a sudden it worked. I guess I wanna know why the getline()
was dependent on the cin.get()
being present.
Any help would be greatly appreciates cause that was frustrating as hell!
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <string>
using namespace std;
struct car {
string make;
int yearBuilt;
};
int main()
{
cout << "How many cars would you like to catalog?" << " ";
int numCars;
cin >> numCars;
car * carArray = new car[numCars];
for (int i = 0; i < numCars; i++)
{
cout << "Car " << ++i << " : ";
--i;
cout << "\nPlease enter the make: ";
cin.get();
getline(cin, carArray[i].make);
cout << "Please enter year built: ";
cin >> carArray[i].yearBuilt;
}
cout << "\n\nHere is your Collection: \n\n";
for (int j = 0; j < numCars; j++)
{
cout << carArray[j].yearBuilt << " " << carArray[j].make << "\n";
}
}