1

First consider this sample C++ code:

std::string input1, input2, input3;
std::cout << "Enter Input 1: ";
std::cin >> input1;
std::cout << std::endl << "Enter Input 2: ";
std::cin >> input2;
std::cout << std::endl << "Enter Input 3: ";
std::cin >> input3;

If for input1 I enter something like "Good day neighbors" then input1 is set to "Good", input2 is set to "day" and input 3 is set to "neighbors". Im not even given the opportunity to set values for input2 and input3.

So my question is: How can I input a string of text that include spaces into a single string without it (for lack of better terminology) breaking up and overflowing into subsequent calls to the input stream?

Thanks in advance to any and all answers received.

Rob S.
  • 3,599
  • 6
  • 30
  • 39
  • fgets. Is a dupe will get link shortly.. – brumScouse Oct 26 '10 at 19:55
  • http://stackoverflow.com/questions/1555731/how-to-take-whitespace-in-input-in-c – brumScouse Oct 26 '10 at 19:59
  • possible duplicate of [How do I iterate over cin line by line in C++?](http://stackoverflow.com/questions/1567082/how-do-i-iterate-over-cin-line-by-line-in-c) – Jerry Coffin Oct 26 '10 at 19:59
  • Neither of those is a duplicate. brumScouse, your question regards a fixed size C-style string as well as an alternative to scanf. I'm working with a C++ Standard library string. The answer would not have helped me. Jerry, your question was asked by someone who already knew getline() existed whereas I did not. Thanks for the links just the same. – Rob S. Oct 26 '10 at 20:07
  • s.: It is a dup of the second one. You just did not know that you wanted a line based solution. – Martin York Oct 26 '10 at 21:33

1 Answers1

7

You can use std::getline:

std::getline(std::cin, input1);
...
std::getline(std::cin, input2);
...
std::getline(std::cin, input3);
Khaled Alshaya
  • 94,250
  • 39
  • 176
  • 234