getline() skipping first even after clear()

早过忘川 提交于 2019-12-04 01:54:45

Make sure you didn't use cin >> str. before calling the function. If you use cin >> str and then want to use getline(cin, str), you must call cin.ignore() before.

string str;
cin >> str;
cin.ignore(); // ignores \n that cin >> str has lefted (if user pressed enter key)
getline(cin, str);

In case of using c-strings:

char buff[50];
cin.get(buff, 50, ' ');
cin.ignore();
cin.getline(buff, 50);

ADD: Your wrong is not probably in the function itself, but rather before calling the function. The stream cin have to read only a new line character \n' in first cin.getline.

cin.clear(); clears any error bits on the stream - it does not consume any data that may be pending.

You want to use cin.ignore() to consume data from the stream.

After you read something there is still 'RETURN' character inside bufor so you have to cin.ignore() after each read.

You can also use cin.sync() to clear the stream. Actualy clear method only clears flags.

There is also option that you can go to the end of stream, with nothing left to read you should write without problems.

std::cin.seekg(0, std::ios::end);

It is up to you what will you use.

use cin.ignore(-1);It will not remove the first character of the input string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!