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.

5
  • fgets. Is a dupe will get link shortly.. Commented Oct 26, 2010 at 19:55
  • stackoverflow.com/questions/1555731/… Commented Oct 26, 2010 at 19:59
  • possible duplicate of How do I iterate over cin line by line in C++? Commented Oct 26, 2010 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. Commented Oct 26, 2010 at 20:07
  • s.: It is a dup of the second one. You just did not know that you wanted a line based solution. Commented Oct 26, 2010 at 21:33

1 Answer 1

7

You can use std::getline:

std::getline(std::cin, input1);
...
std::getline(std::cin, input2);
...
std::getline(std::cin, input3);
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.