Why is cin.ignore() necessary when using “getline” after “cin”, but is not required when using “cin” multiple times?

后端 未结 2 1526
清酒与你
清酒与你 2021-01-14 13:18

In my knowledge when using getline() after cin, we need to flush the newline character in the buffer first, before calling getline(),

2条回答
  •  粉色の甜心
    2021-01-14 13:42

    signed main(){
        /*
         * input is of next two lines
         * Stack Overflow
         * Where developers learn.
         * for more about cin.ignore visit http://www.cplusplus.com/reference/istream/istream/ignore/
         */
        string name, address;
        cin>>name;
        //cin.ignore();
        //cin.ignore(256,'\n');
        getline(cin,address);
        cout << address << endl;
        assert(address == " Overflow"); // breaks if using cin.ignore() or cin.ignore(256,'\n')
        assert(address == "Overflow"); // breaks if using cin.ignore(256,'\n') OR not using any
        assert(address == "Where developers learn."); // breaks if using cin.ignore() or not using ignore
    }
    

    enter the input

    Stack Overflow

    Where developers learn.

提交回复
热议问题