This is my first post. I am completely new to coding and have been messing about with C++ for about a week or so now and thought I'd post some code I have been messing about with. Feel free to make suggestions or cut 'n' paste etc.
This bit of code asks for a username and checks against a stored string. If the username if wrong it loops otherwise a correct username causes goto to break the loop and end the prog.
#include <iostream>
#include <string>
usingnamespace std;
int main()
{
string user;
do { //Beginning of do-while
cout << "What is your username? ";
getline (cin, user); //username input is stored as a string
if (user=="mark") //Correct username will end do-while
goto loggedin; //Jump to loggedin
} while (user!="mark"); //Loop continues until right username is entered
loggedin:
cout << "You are now logged in! "; //end of do-while as a result of correct username.
return 0;
}
This second bit of code is an attempt to validate a username and password using if and else. I really should change all the cin references to getline (cin,string) but it works anyway.
#include <iostream>
#include <string>
usingnamespace std;
int main()
{
string name, pword;
cout << "Please enter your username: ";
cin >> name;
if (name!="mark")
cout << "Incorrect username ";
else
cout << "Please enter your password ";
cin >> pword;
if (pword!="test")
cout << "Incorrect password ";
else
cout << "You are now logged in! ";
return 0;
}
My next step is to combine both bits of code and develop a single prog that will ask for a username and password and continue to loop until both strings are correct. After that I'll have to work out how to limit the number of attempts at the username and/or password. (no hints thanks)
Just some logic flaws in your code example:
If the username was correct, nothing will happen.
Also, if the username was wrong but the password was correct, the user is still logged in.
---
I'd probably do something like this -
1 2 3 4 5 6 7 8
do
{
cout "enter username"
get the name;
if (name is username)
break; //breaks out of the loop
cout "invalid username" //shouldn't get here unless the username is invalid
} while (name != username);
Is this better? I removed the goto and replaced it with Break.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <iostream>
#include <string>
usingnamespace std;
int main()
{
string user;
do { //Beginning of do-while
cout << "What is your username? ";
getline (cin, user); //username input is stored as a string
if (user=="mark") //Correct username will end do-while
break; //Break loop if username is correct
} while (user!="mark"); //Loop continues until right username is entered
cout << "You are now logged in! "; //end of do-while as a result of correct username.
return 0;
}