Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C++ string returning as "

So I am trying to write a function that reverses a string in C++. I’ve figured out most of the code, and when I cout the string, its 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;
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

In this for loop in the first its iteration

  for(int i = str.length(); i >= -1; i--) {
    result+= str[i];
  }

the terminating zero character '\0' is 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 can be outputted as an empty string.

Also you are trying to access the source string using the negative index -1 that 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 for example the following way

  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() };
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading