Search code examples
c++stringreverse

I have to reverse a string but my code is not producing any output -- C++


Given a string S as input. I have to reverse the given string.

Input: First line of input contains a single integer T which denotes the number of test cases. T test cases follows, first line of each test case contains a string S.

Output: Corresponding to each test case, print the string S in reverse order.

why my code is not producing any output? I did this:

#include <iostream>
#include<string>
using namespace std;

int main() {
    int t;
    cin>>t;
    while(t--){
      string s;
      int j=0;
      string res;
      cin>>s;
      int l=s.length();
      for(int i=l-1;i>=0;i--)
      {
         res[j]=s[i];
         j++;
      }
      cout<<res<<endl;
    }
    return 0;
}

input:

1

geeks

output:


Solution

  • std::string is not resized automatically, that's why res[j]=... doesn't work.

    To fix this you can:

    • replace res[j]=... with res.push_back(...)
    • specify string size beforehand, e.g. replace string res; with string res(s.size(), '\0');

    Also note that in production it would be better to do:

    string res = s;
    std::reverse(s.begin(), s.end());
    

    UPDATE. As @Blastfurnace pointed out, an even better version would be:

    std::string res(s.rbegin(), s.rend());