Problems with "||" operator

I'm doing a conversion between units, but when I try to check if the user enters the right input, I always get the error for invalid unit..
If I use just one of the units in the while(or if) arguments like this:
while(unit!="m"), it works just fine.
I thought the "||" operator would make this work for all units, but I guess I have misunderstood how it works.


1
2
3
4
5
6
7
8
9
10
double one;
string unit;
do {
     cout << "Write a number and a unit('m', 'cm', 'in', 'ft')" << endl;
     cin >> one >> unit;
     cout << "'" <<unit<< "'" << endl; //Just to see if I enter the right unit
     if (unit != "m" || unit != "cm" || unit != "in" || unit != "ft") {
          cout << "Invalid unit" << endl;
     }
} while ((unit != "m") || (unit != "cm") || (unit != "in") || (unit != "ft"));
Last edited on
Your || (or) should all be && (and).
Let's say unit == "a".

if (unit != "a" || unit != "b")
What will this evaluate to?
if (a != a || a != b)
if (false || true)
if (true)

You're mixing up logical use of "or" vs colloquial informal English use of "or".

What you're trying to say is, if unit does not equal "a" AND unit does not equal "b".

1
2
3
if (unit != "m" && unit != "cm" && unit != "in" && unit != "ft") {
    cout << "Invalid unit" << endl;
}


See also, for further examples: https://en.wikipedia.org/wiki/De_Morgan%27s_laws
This might make more sense, it's equivalent logic:
1
2
3
if (!(unit == "m" || unit == "cm" || unit == "in" || unit == "ft")) {
    cout << "Invalid unit" << endl;
}
Last edited on
Ah yeah..
Thanks!
> if (unit != "m" || unit != "cm" || unit != "in" || unit != "ft")
This is always true.

Try
if ( !(unit == "m" || unit == "cm" || unit == "in" || unit = "ft") )
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
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main()
{
   vector<string> units = { "km", "m", "cm", "mm", "in", "ft", "yd", "mile" };
   bool ok = false;
   string unit;
   double quantity;

   while ( !ok )
   {
      cout << "Write a number and a unit (";
      for ( auto e : units ) cout << e << " ";
      cout << "): ";

      cin >> quantity >> unit;
      ok = ( find( units.begin(), units.end(), unit ) != units.end() && quantity > 0 );
      if ( !ok ) cout << "Invalid input\n";
   } 

   cout << "You input " << quantity << ' ' << unit << '\n';
}
Last edited on
Topic archived. No new replies allowed.