it keeps asking the question forever

Jun 24, 2012 at 8:20am
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
#include <iostream>
#include <stdio.h>
#include <string>

using namespace std;

int main()
{
    char correct;
    
    do {
        string name;
        double age;


        cout << "what is your first name?" << endl;
        cin >> name;
        cout << "how old are you?" << endl;
        cin >> age;

        cout << "your name is " << name << " and your are " << age << " years old?"  << endl;

        do {
            cout << "is this correct? (y/n)" << endl;
            cin >> correct;
        } while (correct != 'n' || correct != 'y');

    } while (correct == 'n');

    return 0;
}


it keeps asking "is this correct? (y/n)" no matter what you put in




Jun 24, 2012 at 8:45am
1
2
3
4
do {
            cout << "is this correct? (y/n)" << endl;
            cin >> correct;
        } while (correct != 'n' || correct != 'y');


Look carefuly at the while expression, can you figure out what the problem is? Hint: the expression will be true if EITHER one is true. Think about whether you need this do while or not.

Also put these before the do while loop:

1
2
string name;
double age;


I would prefer to use a while loop instead of do while - do whiles are rarely needed and while loops are easier to read.

Hope this helps


TheIdeasMan
Last edited on Jun 24, 2012 at 8:46am
Jun 24, 2012 at 9:53am
how would i use a while loop on this?
Jun 24, 2012 at 10:03am
A while loop is very similar to do while.

1
2
3
4
5
while( /* test condition */) {
   // multiple lines of code here

}


The difference is that the test condition is evaluated first, and is better because you can see the test at the top rather than it being heaps of lines further down.

If you have a lot of code, it is better to call a function or functions to carry out the code in braces. this makes it easier to understand and is much clearer way of doing things.

If in doubt Google.

TheIdeasMan
Jun 24, 2012 at 10:12am
I recommend you fix the first problem before trying to turn the do-while loop into a while loops. Trying to solve many "problems" at once can easily get confusing.
Last edited on Jun 24, 2012 at 10:13am
Topic archived. No new replies allowed.