-1

I am trying to take in a phrase from the user and reverse the order of the words and print this back out. For example "hello world" becomes "world hello".

I have found other questions similar to mine on here and most of the "up-voted" answers suggest doing it this way:

std::list<std::string> input;
std::list<std::string>::iterator iter;
std::string phrase;
std::string word;

std::cout << " Enter the phrase you wish to reverse " << std::endl;
std::cout << " >> ";

std::getline(std::cin, phrase);

std::istringstream iss(phrase);

while (iss >> word) {
    input.push_front(word);
}

for (iter = input.begin(); iter != input.end(); ++iter) {
    std::cout << *iter << " ";
}

However, this does not work for me. When I run the code, it never stops to allow for input. I can not figure out why it does not stop to allow me to type input.

How can I do this so that I can type in a phrase and have the program read it in word by word?

Edit: I am using MS Visual Studio 2015 and compiling using the debug (f5) option.

Alan Stokes
  • 18,815
  • 3
  • 45
  • 64
zkirkland
  • 12,175
  • 3
  • 16
  • 18

1 Answers1

1

It turns out there was a stray "\n" in the input stream and I simply called

std::cin.get();

to get rid of it.

I thought that might be the case but I could not think of how to "flush" the input stream since there is no flush method for cin.

Thank you very much Ankur Jyoti Phukan for your help!

zkirkland
  • 12,175
  • 3
  • 16
  • 18
  • There is a way to flush `std::cin` but it's not obvious. There are several duplicates but [this answer is short and to the point](http://stackoverflow.com/a/32895848/445976). – Blastfurnace Dec 29 '15 at 23:19