-1

The goal of this program is to get user input and then print the words backwards, but still in the order the user typed them in. For example, the user input- "cats and mice are cool", then the program should output "stac dna ecim era looc", but what I am getting is "looc era ecim dna stac". I think that rearranging the words would happen in the main function, but I'm not sure how to get it to print in order. Any help greatly appreciated!

#include <iostream>
#include <cstring>

using namespace std;

void reverse(string input) {
    int size = (int)input.size();

    if(size==1){
        cout << input[size-1];
    }
    else {
        cout << input[size-1];
        reverse(input.substr(0, size-1));
    }
}

int main() {
    string input;
    char choice;    

    cout << "Please enter a string with spaces." << endl;
    getline(cin, input);
    reverse(input);
    cout << endl;
}
YSC
  • 38,212
  • 9
  • 96
  • 149

1 Answers1

2

You're reversing the entire string... split string on spaces, then cycle on splits and call reverse() on every split before printing it.

Furthermore, you can use C++ STL classes for reversing and even result useful in splitting:

#include <iostream>
#include <string>
#include <vector>
#include <sstream>

std::vector<std::string> split(std::string text, char delimiter)
{
    std::vector<std::string> res;
    std::istringstream f(text);
    std::string s;

    while (std::getline(f, s, delimiter)) {
        res.push_back(s);
    }

    return(res);
}

int main() {
    std::string input;

    std::cout << "Please enter a string with spaces." << std::endl;
    std::getline(std::cin, input);

    for(auto s : split(input, ' '))
    {
        std::reverse(s.begin(), s.end());
        std::cout << s << " ";
    }

    std::cout << std::endl;
}
Morix Dev
  • 2,700
  • 1
  • 28
  • 49
  • You can avoid some work by doing the split with the original `getline`. Although there are circumstances in more complex programs where you do want line-input before you do anything else – Lightness Races in Orbit Nov 09 '18 at 17:04