Why does getline not result in the text I expected? [duplicate]

不羁岁月 提交于 2019-12-02 10:59:36

The problem is here:

cin >> options;

You can only extract (>>) from cin when the user hits enter. So the user types 1 Enter and that line executes. Since options is a char, it extracts a single character (1) from cin and stores it in options. The Enter is still in the stdin buffer, since nothing has consumed it yet. When you get to the getline call, the first thing it sees in the buffer is the Enter, which marks the end of input, so getline immediately returns an empty string.

There's lots of ways to fix it; probably the easiest way that fits with the model you're using in your program is to tell cin to ignore the next character in its buffer:

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