C++ getline method not working

蹲街弑〆低调 提交于 2019-12-02 02:58:40

That's because std::cin >> op; leaves a hanging \n in your code, and that's the first thing getline reads. Since getline stops reading as soon as it finds a newline character, the function returns immediately and doesn't read anything more. You need to ignore this character, for example, by using cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); (std::numeric_limits is defined in header <limits>), as stated on cppreference.

This is because you still have the newline character in the buffer which makes getline() stop reading as soon as it encounters it.

Use cin.ignore() to ignore the newline character from the buffer. This will do in your case.

In general, if you want to remove characters from your buffer untill a specific character, use:

cin.ignore ( std::numeric_limits<std::streamsize>::max(), ch )

Use :

cin.ignore ( std::numeric_limits<std::streamsize>::max(), '\n' );

to eat newlines from previous input std::cin >> op;

header - <limits>

Other way would be :

    while (std::getline(std::cin, str)) //don't use string
    if (str != "")
    {
       //Something good received

        break;
    }

As other stated already, the formatted input (using in >> value) start skipping space abd stop when they are done. Typically this results in leaving some whitespace around. When switching between formatted and unformatted input you typically want to get rid of leading space. Doing so can easily be done using the std::ws manipulator:

if (std::getline(std::cin >> std::ws, line)) {
    ...
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!