That is a little homework for myself. I was trying to make a simple program that you entry your name (acts as a password) and if it's on the list then you may access, otherwise (aka else) you're not allowed to access. The problem is I can't put more than two variables for one declaration (eg name == "James" || "Ellen" || "John") which || means OR, correct?

I can do the alternative: if (name = "James") {blah blah} else if (name = "Ellen") {blah blah, same as before one}, etc but that's long. I think OR operator would be easier but it doesn't work. Any suggestions?

#include <iostream>
#include <string.h>
using namespace std;

int main() {
    string name;
    cout << "Password: ";
    cin >> name;
    if (name == "James" || "Ellen" || "John")
    { cout << "\nCommander!\n"; }
    else
    { cout << "\nDENIED!\n"; }
    system("pause");
    return 0;
}

Dani AI

Generated

Short answer: each operand of || must be a boolean expression. In your original test only the first comparison is a boolean; the literal "Ellen" by itself decays to a non-null pointer which converts to true, so the whole condition ends up always true. That’s also why you must use == (not =) for comparisons — using = attempts assignment, not equality.

For a cleaner, scalable solution use a container and test membership instead of many || checks. This also keeps the logic readable and easy to extend:

#include <iostream>
#include <string>
#include <unordered_set>

int main() {
    std::unordered_set<std::string> allowed = {"James", "Ellen", "John"};
    std::string name;
    std::cout << "Password: ";
    std::getline(std::cin, name); // allows spaces in the name
    if (allowed.count(name))
        std::cout << "\nCommander!\n";
    else
        std::cout << "\nDENIED!\n";
}

A few more practical notes tied to the thread: was right that each comparison must be explicit; ’s parentheses work but aren’t required on most compilers (as mentioned). Include <string> (not <string.h>), avoid system("pause") (it's Windows-only and a security concern) — use std::cin.get() or just end the program — and consider normalizing input (trim whitespace, or lowercase) before checking if you want case-insensitive matching.

Recommended Answers

All 3 Replies

name == "James" || "Ellen" || "John") which || means OR, correct?

name == "James" || name == "Ellen" || name == "John"

Thanks but that didn't work. I figured it out. Here is the correct code for learners in the future :)

((name == "James") || (name == "Ellen") || (name == "John"))

Thanks but that didn't work

That's probably your compiler specific req. in using parentheses for that condition, even without those extra parentheses the program compiled/runned fine in my linux gcc

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.