if statements

Hi all,

I am new to c++ and I am trying to implement a simple "password" system that takes a password in the form of a number. Make it so that either of the two numbers is valid, but use only one if statement to do the check.

But no matter what I try I cant get the if statement to check my code. Can any one help? Or give me a hint on what is wrong with my code.

thanks

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

using namespace std;

int main()

{
    string username;
    string password;
    cout << "Enter your username: " << "\n";
    getline( cin, username, '\n' );
    cout << "Enter your password: " << "\n";
    getline( cin, password, '\n' );


    if ( username == "root" && password == "5 or 6")
    {
    cout << "Access allowed" << "\n";
    }

    else
    {
    cout << "Bad username or password. Denied access!" << "\n";

    // returning is a convenient way to stop the program
    return 0;
    }

    // continue onward!

}
Last edited on
"5 or 6" This literally checks for "5 or 6", so I would only have the correct password if I literally type in '5 or 6'. You are wanting to be using the logical or operator, which is '||'.
&& password == "5" || password == "6"

|| = Or
&& = And

looks like your not comparing the length of the password correctly.


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

using namespace std;


int main()

{
    string username;
    string password;
    cout << "Enter your username: " << "\n";
    getline( cin, username, '\n' );
    cout << "Enter your password: " << "\n";
    getline( cin, password, '\n' );


    if (username == "root") {
        if (password.length() == 5 || password.length() == 6 ){
            cout << "Access allowed" << "\n";
        }
        else
            cout << "Bad username or password. Denied access!" << "\n";
        return 0;
        }
        
    // continue onward!
    
}
@Mats you are Genii it worked, Thanks.

@Bdanielz thanks for your reply
Topic archived. No new replies allowed.