Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ cin input not working?

Tags:

c++

#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:
like image 487
Pwnna Avatar asked Dec 22 '22 14:12

Pwnna


1 Answers

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.

like image 148
Etienne de Martel Avatar answered Dec 24 '22 05:12

Etienne de Martel