recursive functions

This code is supposed to take a word that you enter and print back out in reverse so for example if you enter in "Mississippi" it prints out "ippississiM", also it prompts the user for a word to locate within the word they enter before. So if the user wants to locate "issi" it prints out that it was found, and if they enter something that doesnt exist in the word it supposed to print out was not found. This is where my problem is. when i try to enter a word that isnt in the word i get
terminate called after throwing an instance of 'std::out_of_range'
what(): basic_string::substr
Aborted
i dont know what exactly is going wrong with my code. any help would be appreciated.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#include <iostream>
#include <algorithm>
#include <string>

using namespace std;

class Sentence
{
 string word;
public:
    Sentence(): word(""){}
    Sentence(string s): word(s){}
    string reverse();
    bool findword(string s);   
};

string Sentence::reverse()
{
    string s = word;
    string first, second, shortest;
    if (s.length() <= 1)
	return s;
    if (s.length() > 1 )
    {
	first = s.substr(0,1);
	shortest = s.substr(1, s.length() - 1);
	Sentence d(shortest);
	second = d.reverse();
    }
    return second + first;
}

bool Sentence::findword(string s)
{
   string first, second, wrd;
   int j = s.length();
   wrd = word;
   if (wrd.length() < 0)
	return false;
   else 
   {
	first = wrd.substr(0,j);
	second = wrd.substr(1, wrd.length());
	if(first == s)
		return true;
 	else 
	{	
	    Sentence d(second);
	    d.findword(s);
        }
    }
 return false;
}
int main()
{
    string data, word;
    cout << "Enter a word to reverse: ";
    cin >> data;
    while(!cin.eof())
    {
	cout <<"Enter a word you wish to find:   ";
	cin >> word;    	
	Sentence d(data);
    	bool b = d.findword(word);
    	cout << d.reverse() << endl;
    	if(b = true)
    		cout << word << " was found " << endl;
    	else 
		cout << word <<  " was not found " << endl;
    	cout << "Please enter another word or control d to end:  ";
    	cin >> data;
   }
}
Last edited on
1
2
3
4
5
6
7
8
   int j = s.length();
   wrd = word;
   if (wrd.length() < 0) // I don't think that a size_t is ever < 0
	return false;
   else 
   {
	first = wrd.substr(0, j);
	second = wrd.substr(1, wrd.length()); // If pos is greater than the string length, it throws out_of_range. 
Registered users can post here. Sign in or register to post.