#include <iostream>
#include <string>
struct Car{
std::string model;
unsigned int year;
};
int main(){
using namespace std;
int carNum;
cout << "How many cars do you wish you catalog? ";
cin >> carNum;
Car * cars = new Car[carNum];
for (int i=0;i<carNum;i++){
cout << "Car #" << i << endl;
cout << "Please enter the make: ";
getline(cin, cars[i].model);
cout << "Please enter the year made: ";
cars[i].year = cin.get();
}
cout << "Here's your collection" << endl;
for (int i=0;i<carNum;i++){
cout << cars[i].model << " " << cars[i].year << endl;
}
delete [] cars;
return 0;
}
When i execute the program, the getline(cin, car[i].model)
just get skipped over. Why is this?
like this:
Car #2 Please enter the make: Please enter the year made:
Simple reason.
When you do cin >> whatever
, a \n
is left behind (it was added when you pressed Enter). By default, getline
reads until the next \n
, so the next read will simply read an empty string.
The solution is to discard that \n
. You can do it by putting this:
cin.ignore(numeric_limits<streamsize>::max(),'\n');
Just after the cin >> carNum
.
Don't forget to include limits
in order to use numeric_limits
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With