I am trying to write a function that reverses a string. I've figured out most of the code, and when I print the string to std::cout
, it's showing what I need. But, when I test the code, the result is that I got "
from the function. Here's my code:
#include <iostream>
#include <string>
using namespace std;
string result;
string reverseString (string str)
{
for(int i = str.length(); i >= -1; i--) {
result = str[i];
}
cout << result;
return result;
}
CodePudding user response:
In this for
loop, in the very first iteration:
for(int i = str.length(); i >= -1; i--) {
result = str[i];
}
The terminating zero character '\0'
is being written in the first position of the object result
, because the expression str[i]
is equivalent in this case to the expression str[str.length()]
.
So, the result
string is outputted as an empty string.
Also, you are trying to access the source string using the negative index -1
, which results in undefined behavior.
Instead of this for
loop, you could just write:
result.assign( str.rbegin(), str.rend() );
If you want to do the task using the for
loop, then the loop can look like the following:
result.clear();
result.reserve( str.length() );
for ( auto i = str.length(); i != 0; ) {
result = str[--i];
}
Pay attention to that, it is a bad idea to use the global variable result
within the function. The function could look like:
std::string reverseString( const std::string &str )
{
return { str.rbegin(), str.rend() };
}