Beginners Exercise (user == gullible) :)

i am brand new to c++ and any programming whatsoever.
i decided to do the exercises found on http://www.cplusplus.com/forum/articles/12974/ and use online references to help me complete the exercises. i really appreciate these forums, not only because i can ask for criticism on code, but i can read others' criticism from a 3rd person perspective, its a good way to learn. thank you.

anyways, i am doing the "While( user == gullible )" project and i feel like ive completed a part of it, but i cant seem to figure out a way to initiate the loop with "enter anything but 0" i can only figure out how to start it at 1.

here is my code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>

using namespace std;

int main()
{
    int num;
    int loop = 0;

    while (num != loop && loop < 10) {
        loop++;
        cout << "enter any number but " << loop << ".\nNumber: ";
        cin >> num;
        }

    if (loop == 10) cout << "you got too much time on your hands! im out.";
    else if (loop == num) cout << "hey, you werent supposed to enter " << num << "!";
}



1
2
3
4
5
    while (num != loop && loop < 10) {
        loop++;
        cout << "enter any number but " << loop << ".\nNumber: ";
        cin >> num;
        }

this starts it at 1 and works perfectly from then on...


1
2
3
4
5
    while (num != loop && loop < 10) {
        cout << "enter any number but " << loop << ".\nNumber: ";
        cin >> num;
        loop++;
        }

but this kinda screws up number counting, and the number inputted wont match.

im still learning but the necessary thought process for the logic involved is giving me a headache. ive considered a double nested loop instead of the "if" statement at the end, but that threw me for a loop.

does anyone suggest a "more proper" way of doing this?



hello AceFace,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>

using namespace std;

int main()
{
    int num = -1; // initalize num otherwise it's a random number
    int loop = 0;

    for(; loop < 10; loop++) { // for is better since it's in 1 line
        cout << "enter any number but " << loop << ".\nNumber: ";
        cin >> num;
        if(loop == num) // You have to test it before loop++ of course
          break;
        }

    if (loop == 10) cout << "you got too much time on your hands! im out.";
    else if (loop == num) cout << "hey, you werent supposed to enter " << num << "!";
}


that should work. I didn't test it though
thank you, coder777, for the reply and for suggestion. i tested your code and it works great. thanks!
Topic archived. No new replies allowed.