infinite looping, help

This is my program, doing conversions between F and C
The only problem with this is that the while loop will loop infinitely even when the user input 1 or 2. I could change while (ui!= 1 || ui!= 2) to if (ui!= 1 || ui!= 2) but doing so will only allows user to have 2 chances to enter the correct numbers (1 or 2). I want the program to keep asking for the right user input til they get it right. I think I can do it with switch statements but I'm not there yet so I'd love to stick with if and while for this. Please any advice?


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


using namespace std;
double CtoF(double C);
double FtoC(double F);

int main (){

    int ui; // user input
    double C;
    double F;
    cout << "What do you want to convert?" << endl;
    cout << "1. Convert C to F" << endl;
    cout << "2. Convert F to C" << endl;
    cin >> ui;

    while (ui!= 1 || ui!= 2){
    cout << "Please enter 1 or 2 only !" << endl;
    cin >> ui;
    }

    if (ui ==1){
    cout << "enter temp in C: ";
    cin >> C;
    cout << C <<" Celsius = " << CtoF(C) << " Fahrenheit" << endl;
    }else if (ui ==2){
    cout << "enter temp in F: ";
    cin >> F;
    cout << F << " Fahrenheit = " << FtoC(F) << "Celsius" << endl;
    } else {
    cout << "ERROR !" << endl;
    }


}

double FtoC(double F) {
    double C = (F - 32) * 5/9;
    return C;
}

double CtoF(double C) {
    double F = 1.8 * C + 32;
    return F;
}
Nest the while statement again within the while

1
2
3
4
5
6
  while (ui!= 1 || ui!= 2){
    cout << "Please enter 1 or 2 only !" << endl;
    cin >> ui;
        {   while (ui!= 1 || ui!= 2){
            cout << "Please enter 1 or 2 only !" << endl;
                                         }
Thanks for the input. I tried it but it didn't quite work out.
Your mistake is: while (ui!= 1 || ui!= 2)
It should be: while (ui!= 1 && ui!= 2) instead
Last edited on
Change

while (ui!= 1 || ui!= 2){
cout << "Please enter 1 or 2 only !" << endl;
cin >> ui;
}

to

while (ui!= 1 && ui!= 2){
cout << "Please enter 1 or 2 only !" << endl;
cin >> ui;
}
The problem is that ui!= 1 || ui!= 2 can never be false. If ui!= 1 is false then ui!= 2 must be true and vice versa so the whole expression will always be true and the loop will never end.

What you want is probably && instead of ||.
Last edited on
Thank you all. That solved my problem.
I guess I was paying too much attention on syntax instead of algorithm.
Topic archived. No new replies allowed.