Pages

Nested if-else statements


A c++ program example that takes input from user for username and password and then makes decision.


// Program 1

#include <iostream>
#include <string>

using namespace std;

const string userName = "computergeek";
const string passWord = "break_codes";


int main ()
{
    string name, pass;

    cout << "Username: ";
    cin >> name;

    cout << "Password: ";
    cin >> pass;

    if (name == userName)
    {
        if (pass == passWord)
            cout << "You are logged in!" << endl;
        else
            cout << "Incorrect username or password." << endl;
    }
    else
        cout << "Incorrect username or password." << endl;

    return 0;
}


/*A c++ program example that takes input from user for username and if username is correct then only asks for password and makes decision.*/


// Program 2

#include <iostream>
#include <string>

using namespace std;

const string userName = "computergeek";
const string passWord = "break_codes";

int main ()
{
    string name, pass;

    cout << "Username: ";
    cin >> name;

    if (name == userName)
    {
        cout << "Password: ";
        cin >> pass;

        if (pass == passWord)
            cout << "You are logged in!" << endl;
        else
            cout << "Incorrect password." << endl;
    }
    else
        cout << "Incorrect username." << endl;

    return 0;
}

No comments:

Post a Comment