Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple Sentence Reverser in C++

Tags:

c++

I'm trying to build a program to solve a problem in a text book I bought recently and it's just driving me crazy.

I have to built a sentence reverser so I get the following:

Input = "Do or do not, there is no try." Output = "try. no is there not, do or Do"

Here's what I've got so far:

void ReverseString::reversalOperation(char str[]) {
    char* buffer;
    int stringReadPos, wordReadPos, writePos = 0;

    // Position of the last character is length -1
    stringReadPos = strlen(str) - 1;
    buffer = new char[stringReadPos+1];

    while (stringReadPos >= 0) {
        if (str[stringReadPos] == ' ') {
            wordReadPos = stringReadPos + 1;
            buffer[writePos++] = str[stringReadPos--];
            while (str[wordReadPos] != ' ') {
                buffer[writePos] = str[wordReadPos];
                writePos++;
                wordReadPos++;
            }
        } else {
            stringReadPos--;
        }
    }

    cout << str << endl;
    cout << buffer << endl;
}

I was sure I was on the right track but all I get for an output is the very first word ("try.") I've been staring at this code so long I can't make any headway. Initially I was checking in the inner while look for a '/0' character as well but it didn't seem to like that so I took it out.

like image 458
BouncingCzech Avatar asked Dec 04 '22 19:12

BouncingCzech


1 Answers

Unless you're feeling masochistic, throw your existing code away, and start with std::vector and std::string (preferably an std::vector<std::string>). Add in std::copy with the vector's rbegin and rend, and you're pretty much done.

like image 133
Jerry Coffin Avatar answered Dec 30 '22 20:12

Jerry Coffin