Ending loop

When i enter an empty string, the program ends the way it should but it has a weird that comes up and im not sure whats wrong with it.
the message is, (terminate called after throwing an instance of 'std::out_of_range'
what(): basic_string::substr).

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
   #include <iostream>
   #include <string>
  
   using namespace std;
   
   int main(){
  
       string message, pig_message;
	   string::size_type pos;
      bool on;
	do{
        
    cout << "\nEnter the sentence"<<endl;
    getline(cin, message);
    if (message[message.size()-1] != ' ')
    {
        message += ' ';
    }
	while (!(message.length()<1)) {
        pos = message.find(" ");
        string word = message.substr(0,pos);
        message.erase(0,pos+1);

		
        if (word[0] == 'a' || word[0] == 'e' || word[0] == 'i' ||
			word[0] == 'o' || word[0] == 'u') {
			pig_message = word + "yay";
			cout << pig_message + " ";

		}
		else {
			pig_message = word.substr(1) + word[0] + "ay";
			cout << pig_message + " ";
        }
    }
            
	
  
    
    

 if (message==" "){
                on=false;
            }
    
}while(on=true);
return 0;
}
Last edited on
What is the string you enter when the out of range exception happens?
I enter nothing I just hit enter. I thought that's equal to " ".
I thought that's equal to " ".
No, it is an empty string. Hence on line 15 message.size()-1 will be -1.

What happens on line 22 if line 20 message.find(" "); fails?
Hello fivestar,

If your idea is to enter a blank line to quit you will need to move lines 42 - 44 to line 15 and make it look more like this:

1
2
3
4
5
if (message.length() == 0)
{
	on = false;
	continue;
}


To end the loop you need to deal with it just after the input i.e., the "getline". The "continue" will cause a jump to end of the do while loop to check the condition causing the loop to end. Next you will have to change line 46 from while(on = true); to while(on == true);. As it is you assign true to "on" thus making it true and an endless loop. I thing what you meant to do is while (on == true);. This is the equality operator checking to see if "on" is equal to true.

Hope that helps,

Andy

P.S. be sure to initialize "on" before you use it.
Last edited on
Ok thanks
Topic archived. No new replies allowed.