0

I have a function that allows a user to input a word or phrase then display it on a menu but for some reason it will display a word but not a phrase, system crashes when I use more than one word

snippet of my function code:

string GetWord(void){
    string localString = "";
    cout<< "please enter a new word or phrase: ";
    cin >> localString;
    return localString;
}

does anyone know what I have done wrong ? the menu will display a single word but not double.

dbush
  • 205,898
  • 23
  • 218
  • 273

1 Answers1

0

The input operator >> on std::cin stops reading at the first space and so just reads one word. This is the defined behavior.

I assume you would like to read until the user presses enter. You want to read a line. You can use std::getline() to achieve this:

std::string GetWordOrPhrase() {
    std::string localString;
    std::cout << "please enter a new word or phrase: ";
    std::getline(std::cin, localString);
    return localString;
}

BTW: Always use the std:: namespace explicitly in your code. Do not use using namespace std just to spare a few characters. (Code is not (only) about making it work with some compiler, but also a communication means between software developers.)

Johannes Overmann
  • 4,914
  • 22
  • 38
  • Hello, I attempted to use your method but it wouldn't allow me to use the function, just went back into the menu option. I then added a void parameter and the cin >> local string above the getline(), but this time it would only show the second word in menu. – asapemdz97 Mar 25 '19 at 15:50