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

前端 未结 5 1037
旧时难觅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:24

    So basically, cin>>var leaves the '\n' character out of its buffer. So now when you call getline it reads the '\n' character and stops. Therefore we use cin.ignore() to ignore the first character getline reads i.e '\n' when we use it after cin.

    But getline doesn't leave '\n' character instead it stores everything in its buffer till it find '\n' character, then stores '\n' character as well and then stops.

    So in your code when you are using cin.ignore() after a getline and again uses getline to take input, it ignores the first character of the string instead of '\n'. That is why the first character is missing.

    Hope this answers your question.

提交回复
热议问题