c++ cin input not working?

前端 未结 2 1382
爱一瞬间的悲伤
爱一瞬间的悲伤 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 11:45

    After every cin call using insertion operator. You must call cin.ignore() if you want cin.getline () to work.

    As cin>> leaves behind a '\n' character when you press enter and because of that when you use getline () it picks up the \n and takes no input as it finds \n in the input stream which is the default delimiter.

    So you can either do cin.ignore () after every cin>> or simply set a delimiter character cin.getline ()

    0 讨论(0)
  • 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<streamsize>::max(),'\n');
    

    Just after the cin >> carNum.

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

    0 讨论(0)
提交回复
热议问题