mixing cin and getline input issues [duplicate]

早过忘川 提交于 2019-12-02 09:44:52

You need cin.ignore() between two inputs:because you need to flush the newline character out of the buffer in between.

#include <iostream>

using namespace std;

int main() {

string word, line;


cout << "enter a word" << endl;
cin >> word;

cout << "enter a line" << endl;

cin.ignore();
getline(cin,line);

cout << "your word is " << word << endl;
cout << "your line is " << line << endl;

return 0;
}

For your second answer, when you enter whole string in first cin, it takes only one word, and the rest is taken by getline and thus your program will execute without taking input from getline

Demo

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