?
Solved

Using Recursion to reverse a String in Visual C++

Posted on 2011-10-26
10
Medium Priority
?
532 Views
Last Modified: 2012-05-12
Hello,
I am using Microsoft Visual C++ (Win32 Application) to compile the program.

I am trying to reverse a string using recursion function and Class named "Sentence". But I get error when I compile the below code. I have attached the code and the error msg.
Please assist.


#include "stdafx.h"
#include <string>
#include <iostream>
using namespace std;

/**
   Reverse a sentence.
*/
class Sentence
{
public:
   /**
      Creates a Sentence object.
      @param aPhrase a sentence to reverse.
   */
   void read();
   string reverse(const string& a);
 
         
private:
   string phrase;
  
};

void Sentence::read()   
{
	cout << "Please enter a string: " << "\n";
	getline(cin, phrase);
	
}
string Sentence::reverse(const string&  a)
{
   if (a != "")
   {
      string c = a.substr(0, 1);
      string rest = a.substr(1, a.length() - 1);
      Sentence tailSentence(rest);
      a = tailSentence.reverse() + c;
   }
   return a;
}
  
int main()
{
		Sentence greeting;
	   greeting.read();
	   cout << greeting.reverse(const string& a) << "\n";
	  return 0;
}

Open in new window

Doc1.docx
0
Comment
Question by:angel7170
  • 5
  • 5
10 Comments
 
LVL 16

Expert Comment

by:sjklein42
ID: 37034956
Error C2664 - You have declared "a" to be a const (read-only), but then on line 38 you are trying to modify it.

Error C2660 - You have declared reverse to take an argument (a), but then on line 38 you are not passing any argument to reverse when you call it

Error C2143 - On line 47, did you mean to pass "phrase" to the reverse function?  Looks like cut-and-paste error.  This triggered three error messages.
0
 

Author Comment

by:angel7170
ID: 37039721
Thank you. What should I be doing to modify them? I just started learning C++...sorry
0
 
LVL 16

Expert Comment

by:sjklein42
ID: 37039890
No problem.  Good luck.

There are two ways to fix it.  The purest approach is to declare a local variable inside the reverse function and use that variable inside the function instead of "a".  That way you don't modify the readonly "a" argument to the function.  But you need to declare a local variable and copy the input into that variable as an extra step.

The other approach is to get rid of the "const" in the declaration of the "a" argument to the reverse function.  This is a little less of a purist solution, but is the way I would do it.  I think it is perfectly fine.

1. Get rid of the "const" on line 17 in the function prototype.

 string reverse(string& a);

2. Get rid of "const" on line 31 in the function argument list.

string Sentence::reverse(string&  a)

Now you are allowed to modify "a" within the reverse function.

You still have a problem with line 47, where you simply need to call reverse(a).  You do not need the const & when actually calling the function:

         cout << greeting.reverse(a) << "\n";
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 

Author Comment

by:angel7170
ID: 37040614
Thank you.

I changed the code as you said . There are no more errors but I get the exception error "string subscript out of range" .

Please help.

Thank you
#include "stdafx.h"
#include <string>
#include <iostream>
using namespace std;

/**
   Reverse a sentence.
*/
class Sentence
{
public:
   /**
      Creates a Sentence object.
      @param aPhrase a sentence to reverse.
   */
   void read();
   string reverse(string& a);
 
         
private:
   string phrase;
  
};

void Sentence::read()   
{
	cout << "Please enter a string: " << "\n";
	getline(cin, phrase);
	
}
string Sentence::reverse(string&  a)
 {
size_t n = a.size();
if(n == 1)
cout << a << endl;
else
{
cout << a[n-1];
string b = a.substr(0, n-1);
reverse(b);
}
return a;
}
  
int main()
{
		Sentence greeting;
		greeting.read();
		string aphrase;
		cout << greeting.reverse(aphrase) << "\n";
		 return 0;
}

Open in new window

0
 
LVL 16

Expert Comment

by:sjklein42
ID: 37040790
Looking a little deeper at your code, the reverse function is a bit schizophrenic.  Is it supposed to return the reversed string, or print it out?  It is doing a bit of each.  Here are some changes so that the reverse function will print out the reverse of its input and returns void (nothing).

Note that I was able to make the "a" argument read-only again (const) since it is no longer modified within the reverse function.

We can do it the other way, too, if you like.  (This would involve changing the reverse function to return a string value and not do any output itself.)

There is another sloppiness in the way that "phrase" and "aphrase" are being handled.  The "read" function puts its input into the private, but static, variable "phrase".  However, at the end of your program, you declare "aphrase" local variable and pass that to reverse.  You simply need to pass "greeting.phrase" to reverse to get the recursion started.

Try this:

#include "stdafx.h"
#include <string>
#include <iostream>
using namespace std;

/**
   Reverse a sentence.
*/
class Sentence
{
public:
   /**
      Creates a Sentence object.
      @param aPhrase a sentence to reverse.
   */
   void read();
   void reverse(const string& a);
 
         
private:
   string phrase;
  
};

void Sentence::read()   
{
	cout << "Please enter a string: " << "\n";
	getline(cin, phrase);
	
}
void Sentence::reverse(const string&  a)
{
	size_t n = a.size();
	if(n == 1)
		cout << a << endl;
	else
	{
		cout << a[n-1];
		string b = a.substr(0, n-1);
		reverse(b);
	}
}
  
int main()
{
	Sentence greeting;
	greeting.read();
	greeting.reverse(greeting.phrase) << "\n";
	return 0;
}

Open in new window

0
 

Author Comment

by:angel7170
ID: 37040857
Thanks for explaning.

But I get errors when I compile , please see the attached
Doc1.docx
0
 
LVL 16

Accepted Solution

by:
sjklein42 earned 2000 total points
ID: 37040983
Ok.  There are two problems.  One is easy, the other not quite as easy.

The easy one.  When I changed "reverse" to do the output itself, I messed up.  On line 48, the program was also printing out the newline "\n" and I missed that.  I should have made line 48 into two separate lines:

greeting.reverse(greeting.phrase);
cout << "\n";

Open in new window


The other problem is that the "phrase" variable is private within the greeting object, so we are not allowed to refer to it outside in the main program.  Best way to fix this is to change "read" so it returns a string instead of storing it in a private variable within the greeting object.

Then, the main program can pass that string back into reverse.

Try this:

Remove the Private declaration of phrase and move it inside "read".  Also have "read" return that value.  Pick the value up in main where you call "read" and put it into a local variable aphrase.  Pass aphrase to "reverse" to start the recursion.

#include "stdafx.h"
#include <string>
#include <iostream>
using namespace std;

/**
   Reverse a sentence.
*/
class Sentence
{
public:
   /**
      Creates a Sentence object.
      @param aPhrase a sentence to reverse.
   */
   string read();
   void reverse(const string& a);
 
         
string Sentence::read()   
{
	string phrase;
	cout << "Please enter a string: " << "\n";
	getline(cin, phrase);
	return phrase
}
void Sentence::reverse(const string&  a)
{
	size_t n = a.size();
	if(n == 1)
		cout << a << endl;
	else
	{
		cout << a[n-1];
		string b = a.substr(0, n-1);
		reverse(b);
	}
}
  
int main()
{
	Sentence greeting;
	string aphrase;
	aphrase = greeting.read();
	greeting.reverse(aphrase) << "\n";
	return 0;
}

Open in new window

0
 

Author Comment

by:angel7170
ID: 37041030
You are awesome. Your code worked perfect.
#include "stdafx.h"
#include <string>
#include <iostream>
using namespace std;

/**
   Reverse a sentence.
*/
class Sentence
{
public:
   /**
      Creates a Sentence object.
      @param aPhrase a sentence to reverse.
   */
   string read();
   void reverse(const string& a);

};

string Sentence::read()   
{
	string phrase;
	cout << "Please enter a string: " << "\n";
	getline(cin, phrase);
	return phrase;
	
}
void Sentence::reverse(const string&  a)
{
	size_t n = a.size();
	if(n == 1)
		cout << a << endl;
	else
	{
		cout << a[n-1];
		string b = a.substr(0, n-1);
		reverse(b);
	}
}
  
int main()
{
	Sentence greeting;
	string aphrase;
	aphrase = greeting.read();
	greeting.reverse(aphrase);
	cout << "\n";
	return 0;
}

Open in new window

0
 

Author Comment

by:angel7170
ID: 37041032
Thank you very much for your assistance.
0
 
LVL 16

Expert Comment

by:sjklein42
ID: 37041202
Thanks.  Good luck.
0

Featured Post

How to Use the Help Bell

Need to boost the visibility of your question for solutions? Use the Experts Exchange Help Bell to confirm priority levels and contact subject-matter experts for question attention.  Check out this how-to article for more information.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

I think the Typed DataTable and Typed DataSet are very good options when working with data, but I don't like auto-generated code. First, I create an Abstract Class for my DataTables Common Code.  This class Inherits from DataTable. Also, it can …
The ECB site provides FX rates for major currencies since its inception in 1999 in the form of an XML feed. The files have the following format (reducted for brevity) (CODE) There are three files available HERE (http://www.ecb.europa.eu/stats/exch…
Is your data getting by on basic protection measures? In today’s climate of debilitating malware and ransomware—like WannaCry—that may not be enough. You need to establish more than basics, like a recovery plan that protects both data and endpoints.…
Screencast - Getting to Know the Pipeline
Suggested Courses

850 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question