2

I have a for loop that returns the user's input backwards. They enter a string, and the loop reverses it. Here's what it looks like:

string input;                          //what user enters
const char* cInput = input.c_str();    //input converted to const char*

for(int i = strlen(cInput) - 1; i >= 0; i--)
   cout << input[i];     //Outputs the string reversed

Instead of having cout << input[i], how can I set input[i] as the value of a new string? Like I want to have a string called string inputReversed and set it equal to input[i].

In other words, if input == hello, and input[i] == olleh, I want to set inputReversed equal to olleh.

Is this doable? Thanks!

Archie Gertsman
  • 1,601
  • 2
  • 17
  • 45
  • Consider using [`std::string::size`](http://www.cplusplus.com/reference/string/string/size/) instead of converting to a `const char*` and using `strlen`. – Chris Drew Oct 20 '15 at 21:49

4 Answers4

2

Just declare the output string and append to it, either with += or the append member function:

string inputReversed;

for(int i = input.size() - 1; i >= 0; i--)
    inputReversed += input[i];         // this
//  inputReversed.append(input[i]);    // and this both do the same thing

Note that you don't need c_str and strlen, you can simply use the size or length member function.

You can also make the code more readable by using std::reverse:

string inputReversed = input;
std::reverse(inputReversed.begin(), inputReversed.end());

Or std::reverse_copy, since you're making a copy of the original string anyway:

string inputReversed;
std::reverse_copy(input.begin(), input.end(), std::back_inserter(inputReversed));
Emil Laine
  • 41,598
  • 9
  • 101
  • 157
  • Thanks, I like this method. And I didn't use the reverse function because I wanted to make a palindrome detector as beginner practice :) – Archie Gertsman Oct 20 '15 at 22:04
2
string inputReversed(input.rbegin(), input.rend());
Chris Drew
  • 14,926
  • 3
  • 34
  • 54
1

If i understand what you are asking you want to have a variable to store the reversed string and output that? If so you can just do this

string input, InputReversed; 
                         //what user enters
const char* cInput = input.c_str();    //input converted to const char*

for(int i = strlen(cInput) - 1; i >= 0; i--){

    InputReversed += input[i];     

}
cout << InputReversed;  //Outputs the string reversed
Dragonrage
  • 205
  • 6
  • 17
0

Going off of this thread may help you. How do I concatenate const/literal strings in C?

It seems like what you want is to create a new string which at the end of the loop will contain the backwards input.

string input;                          //what user enters
const char* cInput = input.c_str();    //input converted to const char*
char inputReversed[len(input)];

for(int i = strlen(cInput) - 1; i >= 0; i--)
   output = strcpy(output, input[i]);     //Outputs the string reversed
Community
  • 1
  • 1