1

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 Answers1

5

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

vishal
  • 2,258
  • 1
  • 18
  • 27
  • Thx!, I thought that with different strings there was no need to do things like that... can i assume that what happen is like the cin holds the info and blocks the input to other strings? is better to use just one of them (cin or getline?) – Gary Andres Gutierrez Fajardo Oct 24 '15 at 09:59
  • This might help clearing your doubts.. http://stackoverflow.com/questions/4745858/stdcin-getline-vs-stdcin – vishal Oct 24 '15 at 10:05