c++ cin input not working?

前端 未结 2 1383
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-18 11:41
#include 
#include 

struct Car{
    std::string model;
    unsigned int year;
};

int main(){
    using namespace std;

    int carNum         


        
2条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-18 12:07

    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::max(),'\n');
    

    Just after the cin >> carNum.

    Don't forget to include limits in order to use numeric_limits.

提交回复
热议问题