Home > Software engineering >  Code can't reverse the string. It prins empty
Code can't reverse the string. It prins empty

Time:02-11

#include <iostream>
#include <string.h>

using namespace std;

int main()
{
    string x;
    cout << "input";
    cin >> x;
    
    int y = x.size();
    
    string f;
    
    for (int i = 0; i <= y-1; i  ){
    
    f[i] = x[y-(1 i)];
    f[y] = '\0';
    
    }
    
    cout << f << endl;
    return 0;
    
}

As the code above shows, i am tring to reverse the string user's input. "cin >> x;" store the string input as x. "int y = x.size..." pick the size of the string. "f[i] = x[y-(1 i)];" reverses the string input. Example:

Let the input be "hello",
So y=5.
f[0] = x[4] = o;
...
f[3] = x[1] = e;
f[4] = x[0] = h;

"cout << f << endl;" should print f. BUT the code does not work. I fear that it is because "f[i] = x[y-(1 i)]; f[y] = '\0';" is inside keys {} and so does not change the value of f. Is it the problem? how to fix it?

CodePudding user response:

To create a reversed copy of the source string you could just write

string f( x.rbegin(), x.rend() );

If to use the approach with the for loop then the loop can look the following way

for ( auto n = x.size(), i = 0; i < n; i   )
{
    f  = x[n - i - 1];
}

Before the for loop you could reserve required memory for the string f like

f.reserve( x.size() );

As for your code then at least you may not use the subscript operator with the empty string f. And there is no need to add explicitly the terminating zero character '\0'.

Moreover if before the for loop you will write

string f(y,' ');

as it was advised nevertheless this statement

f[y] = '\0';

invokes undefined behavior.

CodePudding user response:

to use the same logic as you have you need

string f = x;

or

string f(y,' ');

to allocate f large enough to hold the resulting string

CodePudding user response:

Try this out

Simply loop through the string the user provide and start taking the character from the last index value minus one(-1) to the first index value and append it to the variable f

For Example


#include <iostream>
#include <string.h>

using namespace std;

int main()
{
    string x;
    cout << "digite algo\n";
    cin >> x;
    
    int y = x.size();
    
    string f;
    
    for (int i = y-1; i>=0; i--){
    
    f = x.at(i);
    
    }
    
    cout << f << endl;
    return 0;
    
}

  • Related