the || operator checking for strings allows anything to be true

Hi! I have just started making a simple text-adventure/Rpg, and i'm currently trying to get the basic movement working. I decided to let the program check for specific words and move according to them, and that's the code I came up with:

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>
#include <stdio.h>      /* printf, scanf, puts, NULL */
#include <stdlib.h>     /* srand, rand */
#include <time.h>       /* time */
#include <ctime>
#include <string>
#include <sstream>


using namespace std;


int main()

{

    string direction;


    while(true){

    cout << "Enter your direction!\n\n";
    getline(cin, direction);

    if (direction == "West" || "w")
    cout << "\nYou are going West!\n\n";

}}


As long as I have a single word to check for, it works just as intended. But once I add in multiple words for the same value, the program will allow ANYTHING to be true! How do I make the program only accept the given words?
|| is a binary operator that returns true if at least one of the operands are true. In your code the second operand is "w", which is treated as true (because it's not null), so the whole expression is always true. What you have to do is to compare the variable on both sides of the operator.

 
if (direction == "West" || direction == "w")
Last edited on
damn! Good catch, that fixed it! Thanks for helping me out!
Topic archived. No new replies allowed.