Question on how to fix my code

I have a program that asks for your username then asks for your password, when i compile it, it gives me both options of the password being correct and wrong how could i fix this.


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

int main(void)
{
int password;
password = 'billy';

string username;
username = 'billyeastep9';
string userinput;

do

{

cout<<"Enter username..."<<endl;
cin>>userinput;

if (userinput == username);

{

cout<<"Enter password...";
cin>>password;

}
}

while (userinput == username);

if (password == 'billy');
cout<<"Welcome!"<<endl;


if (password != 'billy');
cout<<"Access denied, try again"<<endl;

return 0;
}

you'll probably have to compile it yourself to see what im trying to say, any help would be appreciated. Ask me any questions you need because i know i was not very precise...
I hope this can help you:

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

using namespace std;

int main() {
    string password = "billy";
    string username = "billyeastep9";
    string userinput;

    do {
        cout << "Enter username... " << endl;
        cin >> userinput;
        if (userinput == username) {
            cout << "Enter password... " << endl;
            cin >> password;
        }
    } while (userinput != username);

    if (password == "billy")
        cout << "Welcome!" << endl;
    else
        cout << "Access denied, try again" << endl;

    return 0;
}
Last edited on
how could i prevent it from giving me an error saying that else without a previous if statement when there clearly is an if statement before the else statement...
Last edited on

Hi,

how could i prevent it from giving me an error saying that else without a previous if statement when there clearly is an if statement before the else statement...


You had semicolons at the end of the if statements, these are actually interpreted as null statements. Also, always use braces, even if there is only 1 statement. This will save you one day when you add more code. You can see elaleph's code doesn't have the semicolons.


20
21
22
23
24
25
    if (password == "billy") {
        std::cout << "Welcome!\n";
    }
    else {
        std::cout << "Access denied, try again\n";
    }


Please always use code tags in the future. Use the <> formatting button.

If doing a do loop, put the while part on the same line as the closing brace, so it doesn't look like a while loop.

http://www.cplusplus.com/articles/z13hAqkS/


Good Luck !!
Last edited on
Topic archived. No new replies allowed.