0
#include <iostream>
#include <string>

using namespace std;

char rerun;

string reverse(string x){
    string x_out = x;

    for(int i = 0; i < x.size(); i++){
        if(i == x.size() - 1){
            x_out[i] = x[0];
        } else {
            x_out[i] = x[x.size() - i - 1];
        }
    }

    return x_out;
}

int main(){
    do {
        string in_string;

        cout << endl;
        cout << "This program will reverse any string you input." << endl;
        cout << "-----------------------------------------------" << endl;

        cout << "Enter a string: ";
        getline(cin, in_string);

        cout << "Your reversed string is:" << endl;
        cout << endl;
        cout << reverse(in_string);
        cout << endl;

        cout << "RUN PROGRAM AGAIN? (Y/N): ";
        cin >> rerun;
    } while (rerun == 'y' || rerun == 'Y');
}

Hey, I am having problems with this do-while loop. I'm trying to accept user input (the variable rerun) to determine whether to run the program again or not. What it is supposed to do is run int main() again if the user inputs 'Y' or 'y'. But for some reason, it won't run the reverse() function when it is called. Below is what the program actually runs like on my terminal. Anyone have any tips? Thanks.

This program will reverse any string you input.
-----------------------------------------------
Enter a string: Woah wait
Your reversed string is:

 tiaw haoW
RUN PROGRAM AGAIN? (Y/N): Y

This program will reverse any string you input.
-----------------------------------------------
Enter a string: Your reversed string is:


RUN PROGRAM AGAIN? (Y/N):
Drew Dormann
  • 50,103
  • 11
  • 109
  • 162
  • `getline` will consume the line from the first argument and discard the trailing `\n`. Formatted input operator `>>` will consume up to the first whitespace character (like `\n`) but not discard it. When you call `getline` in the second loop iteration, it sees a `\n` at the start of the line and terminates without waiting for input. Don't mix formatted input operations and `getline`. – JohnFilleau Mar 11 '20 at 17:55
  • @John What would be the appropriate way of storing the entire string into in_string then? – Ismael Nunez Mar 11 '20 at 18:05
  • You either always use `getline` on a stream, or you always use `>>`. (this is a generalization - you CAN mix them. It's legal, but it requires extra steps) Since one of your steps requires a full line, that means you should always use `getlne`. That means you want your rerun character to instead be a rerun string. When checking for reruns, use `getline` to get a string, and rerun if it equals `"Y"` or `"y"`, not `'Y'` or `'y'`. – JohnFilleau Mar 11 '20 at 18:08
  • Thank you so much! – Ismael Nunez Mar 11 '20 at 18:12

0 Answers0