Stopping while loop

I was wondering if I can stop the while loop in the 12th line somehow instead of using break; in the 24th line. I tried :
while(nr != 5 || t == 10)
but it won't stop the program after t == 10, it just keeps going.

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
  #include <iostream>
using namespace std;
int main()
{
    int nr, t = 0;
    cout << "Type your first number: \n";
    cin >> nr;
    if(nr != 5)
    {
        t++;
    }
    while(nr != 5)
    {
        cout << "Type any number: \n";
        cin >> nr;
        if(nr == 5)
        {
            cout << "You can't type 5 \n";
        }
        else t++;
        if(t == 10)
        {
            cout << "Patience my friend, you've won" << endl;
            break;
        }

    }
    return 0;
}
closed account (z05DSL3A)
while(nr != 5 && t != 10)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>

int main()
{
    const int NREQUIRED = 10 ;
    const int TABOO_NUMBER = 5 ;

    int cnt = 0 ;
    int number ;
    while( cnt < NREQUIRED &&
           std::cout << cnt+1 << ". type any number other than " << TABOO_NUMBER << ": " &&
           std::cin >> number )
    {
        if( number == TABOO_NUMBER ) std::cout << "You can't type " << TABOO_NUMBER << '\n' ;
        else ++cnt ;
    }

    std::cout << "Patience my friend, you've won\n" ;
}
Okay, I got the idea what u meant. I have another problem. Every time when I type any number that is higher than the current i i.e i = 4 and I type nr = 5 the code stops.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
using namespace std;
int main()
{
    int nr, t = 0, i = 0;
    do
    {
        cout << "Type any number that isn't: " << i << endl;
        cin >> nr;
        if(nr == i) break;
        else i++;
    }
    while(nr != i);
    return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>

int main()
{
    int number ;

    for( int cnt = 100 ;

         std::cout << "type any number not higher than " << cnt << ": " &&
         std::cin >> number && number <= cnt ;

         ++cnt ) ;

    std::cout << "you typed in a wrong number. quitting\n" ;
}
Could you explain to me how the 9th and 10th lines work? Those && ?
Lines 9 and 10 together form the condition of the for loop.

In English, the condition would read:
if "type any number not higher than ... etc." is printed on stdout (line 9) and
if the user entered a number (first part of line 10) and
if the number is less than or equal to count (second part of line 10)


&& is the logical AND operator.

In effect, come out of the loop if
a. the user entered something which is not a number (std::cin >> number failed)
or b. if the number entered was larger than cnt
Last edited on
Topic archived. No new replies allowed.