problem in making program using loop

Actually i am trying to make a quiz program using do while loop.what i want to know is that how could i make the loop exit after repeating simply three times.If the user fails to answer the question in three attempts the programme should exit.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include<string.h>
using namespace std;

int main()
{string answer;
do{
    cout<<"who is the founder of facebook"<<endl;
    getline(cin,answer);
}
while(answer!="mark zuckerberg");
{
    cout<<"you are right"<<endl;
    return 0;
}

}
Last edited on
At the moment your code will go in an infinite loop until the user enters the correct answer. You'll need to implement a variable that will count the number of times the loop has been iterated.

1
2
3
4
5
6
7
8
9
10
//using declarations instead of using directive
using std::cout; using std::cin; using std::endl;

//initialise variables
string answer = "";
int count = 0;

pseudo code...
increment count
while count is less than 3


Also, why do you have a set of braces at line 12 and line 15?
Last edited on
In this case you will have to create a counter increase it inside the loop and check it is value in loop condition, or you could write a for loop and check if the answer is correct, if it is you break out of the loop.

1
2
3
4
5
6
7
8
string answer;
int counter = 0;

do {
    cout << "who is the founder of facebook";
    getline(cin, answer);
    counter++;
} while (counter < 3 && answer != "mark zuckerberg");


Edit: i didn't notice someone already posted a solution.
Last edited on
thanks for reply integralfx and CodeBlob. That solved my problem.Many thanks. Integralfx i just have the habit of writing everything in braces so i do not get confused.Again thanks
Last edited on
Topic archived. No new replies allowed.