C++ iostream: Using cin >> var and getline(cin, var) input errors

前端 未结 5 1043
旧时难觅i
旧时难觅i 2020-12-06 23:11

I\'m creating a simple console application in C++ that gets string and char inputs from the user. To make things simple, I would like to use the string and

5条回答
  •  甜味超标
    2020-12-06 23:19

    cin>>var;

    only grabs the var from the buffer, it leaves the \n in the buffer, which is then immediately grabbed up by the getline

    So, following is just fine, (if I understood correctly your problem)

    cin>>var;
    cin.ignore();     //Skip trailing '\n'
    getline(cin, var);
    

    As per your edited post

    You don't have to use cin.ignore(); for geline

    This extracts characters from buffer and stores them into firstName or (lastName) until the delimitation character here -newline ('\n').

提交回复
热议问题