mixing cin and getline input issues [duplicate]

倾然丶 夕夏残阳落幕 提交于 2019-12-25 03:39:14

问题


Im doing exercices from c++ primer, and trying to do a program that recieves as input a word and a line. If when i ask for a word (with cin) I press enter, then the program just skips the next lines and doest ask for a line (with the getline)... and if i write an entire phrase in the cin (like "hello beautifull world") then the first word ("hello") is captured by the cin and the others two words ("beautifull world") by the getline.

i understand that in the cin, when i input a space, it cuts the input. what i dont uderstand are two things:

1.- why if i end the input (in the cin) with enter it skips all the rest of code? (is there a solution for that?)

2.- why if i write an entire phrase in the cin, it assign the other two word to the getline before to execute the cout << "enter a line" << endl; ?

Thx! sorry for my english C:

 #include <iostream>
 #include <string>
 using namespace std;

 int main() {

string word, line;

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

cout << "enter a line" << endl;
getline(cin, line);

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

return 0;
}

回答1:


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



来源:https://stackoverflow.com/questions/33316564/mixing-cin-and-getline-input-issues

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