I wrote a recursive function that reverses the order of words, but the function does not give an output when it takes a sentence as input. The following is my code:
void reverseWord(void){
string word;
if(!(cin>>word)){
return;
}
reverseWord();
cout<<word<<" ";
}
But in the "C++ Primer(fifth edition)", there is such a sample code for reading an unknown number of strings:
int main(){
string word;
while(cin>>word)
cout<<word<<endl;
return 0;
}
What does the expression “!(cin<<word)” return? And how to modify the if-statememt?
There is nothing in your code that is causing the infinite recursion! The problem is generating eof (end-of-file) on the input stream.
Generating eof from the keyboard, (i.e., from
std::cin)On Windows systems, you can press
Ctrl+Zto generate an eof condition from the keyboard. That will causecin.eof()to become true, and subsequent input will fail.It's a little tricky, though, because
Ctrl+Zhas to be the first character of a line for this to work. So, after you enter a sentence, you will have to do three things.Enterto input the sentence. That allows your program to process the sentence. Nothing will be displayed, however, until the end of step 3.Ctrl+Zat the start of the next line.Enterto input the theCtrl+Zfrom step 2.After step 3, the sentence will be displayed with its words in reverse order.
On Unix-like systems,
Ctrl+Dwill sometimes do the same thing.Note that
Ctrl+ZandCtrl+Dare not "eof characters." There is no such thing. They are regular (albeit, unprintable) characters, which, under certain system-dependent circumstances, will causestd::cinto be placed into an end-of-file state.Demonstration using
std::stringstreamOne way to demonstrate that your program is fine, is to add a
std::istream&as an argument, and use astringstream. When the stringstream runs out of characters, it will fail.Here is the complete program.
Output
Use a while loop
A commenter pointed out that you could solve this using a while-loop, instead of recursion. That requires storing the words for later retrieval. A
std::stackwould do the job nicely.