loop help

once it hits the else i want to be able to run the program again so they can try it again i know i need loop but i don't know how

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
#include <iostream>
#include <string>

using namespace std;

int main()
{
string ans, name;
		
		cout << "Hello what is your name" << endl;
		cin >> name;
		cout << "Nice to meet your " << name << endl;
		cout << "How is your day " << name << endl;
		cin >> ans;
// if (ans.eguals("good"))
	if (ans == "good")
		{
			cout << "Thats good, enjoy the rest of your day" << endl;
		}
// if (ans.equals("fine"))
	else if (ans == "fine")
		{
			cout << "Just fine not good" << endl;
		}
// if (ans.equals("bad"))
	else if (ans == "bad")
		{
			cout << "Thats too bad, i hope you have a better day tomarrow" << endl;
		}
//if (ans.equals("great"))
	else if (ans == "great")
		{
			cout << "thats awesome to hear" << endl;
		}
//if (ans.equals("terible"))
	else if (ans == "terible")
		{
			cout << "thats terible to here, im sorry" << endl;
		}
	else
		{
			cout << "sorry thats none of the choices try good, fine, bad, great, or terible, thank you" << endl;
		}
return 0;
}
where is the loop?

1
2
3
4
5
6
7
8
9
10
11
12
13

boolean tryagain = true;
while(tryagain)
{

if(ans.equals("good"))
{
...
tryagain = false;
}
...

}


traagain will remain true and the loop will continue to run until you make it false
Last edited on
you can place continue;/break;
your code will be like:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
...
while(true)   //infinite loop
{
    cout << "How is your day " << name << endl;
    cin >> ans;
// if (ans.eguals("good"))
    if (ans == "good")
    {
	cout << "Thats good, enjoy the rest of your day" << endl;
        break;    //here it will exit the loop the same for all the else if
    }
...
    else
    {
	cout << "sorry thats none of the choices try good, fine, bad, great, or terible, thank you" << endl;
         continue;     //will reloop (test the condition and since it's true reloop)
    }
}




P.S.: in line 38 you mistyped hear


Edit: or you can do like Gkneeus told you
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
...
int tryagain=1;    //or bool
while(tryagain)   //infinite loop
{
    tryagain=0;
    cout << "How is your day " << name << endl;
    cin >> ans;
// if (ans.eguals("good"))
    if (ans == "good")
    {
	cout << "Thats good, enjoy the rest of your day" << endl;
    }
...
    else
    {
	cout << "sorry thats none of the choices try good, fine, bad, great, or terible, thank you" << endl;
        tryagain=1;
    }
}
Last edited on
jewelcpp it comes up with 1 failed it wont run
Topic archived. No new replies allowed.