I'm mostly new to C# and I've been writing code to practice.
I've written some code where you enter a line of text, or a "login key", and I want to make it where you can confirm that login key.
Here's the code I've done so far, I will use "//" on the part I'm stuck on. (Wont include any unnecessary code.)
Console.WriteLine("Please enter a login key.");
string Key = Console.ReadLine();
Console.WriteLine("You entered, " + Key + " as your login key!");
Console.WriteLine("Are you sure you want to choose this as your login key? "); // This is where I'm stuck at, got no idea how to do a yes/no prompt.
}
Any help would be greatly appreciated.
You can easily go overboard on these Console login scripts. Here's my contribution:
bool confirmed = false;
string Key;
do {
Console.Write("Please enter a login key: ");
Key = Console.ReadLine();
Console.WriteLine("You entered, " + Key + " as your login key!");
ConsoleKey response;
do
{
Console.Write("Are you sure you want to choose this as your login key? [y/n] ");
response = Console.ReadKey(false).Key; // true is intercept key (dont show), false is show
if (response != ConsoleKey.Enter)
Console.WriteLine();
} while (response != ConsoleKey.Y && response != ConsoleKey.N);
confirmed = response == ConsoleKey.Y;
} while (!confirmed);
Console.WriteLine("You chose {0}!", Key);
Console.ReadLine();
Sample output:
Please enter a login key: potato
You entered, potato as your login key!
Are you sure you want to choose this as your login key? [y/n] a
Are you sure you want to choose this as your login key? [y/n] s
Are you sure you want to choose this as your login key? [y/n] l
Are you sure you want to choose this as your login key? [y/n] d
Are you sure you want to choose this as your login key? [y/n] k
Are you sure you want to choose this as your login key? [y/n] f
Are you sure you want to choose this as your login key? [y/n] d
Are you sure you want to choose this as your login key? [y/n] n
Please enter a login key: banana
You entered, banana as your login key!
Are you sure you want to choose this as your login key? [y/n] y
You chose banana!
I remake it like a utils class I hope it's gonna be usefull:
class UtilsConsole
{
public static bool Confirm(string title)
{
ConsoleKey response;
do
{
Console.Write($"{ title } [y/n] ");
response = Console.ReadKey(false).Key;
if (response != ConsoleKey.Enter)
{
Console.WriteLine();
}
} while (response != ConsoleKey.Y && response != ConsoleKey.N);
return (response == ConsoleKey.Y);
}
}
Use Console.ReadKey();
Console.WriteLine("Press 'y' if you would like awesome!");
ConsoleKeyInfo cki = Console.ReadKey();
if (cki.Key.ToString() == "y")
{
//do what you need for yes
}else {
// presses something other then Y
}
I prefer to create a reusable method to handle all future questions. Very simplified version to illustrate basics.
void Main(string[] args)
{
if(PromptConfirmation("Did you answer yes?"))
{
//todo: Handle positive response
}
}
private bool PromptConfirmation(string confirmText)
{
Console.Write(confirmText + " [y/n] : ");
ConsoleKey response = Console.ReadKey(false).Key;
Console.WriteLine();
return (response == ConsoleKey.Y);
}
You can use a while loop
bool confirmed = false;
while(!confirmed)
{
Console.WriteLine("Please enter a login key.");
string Key = Console.ReadLine();
Console.WriteLine("You entered, " + Key + " as your login key!");
Console.WriteLine("Are you sure you want to choose this as your login key? [yes/no]");
string option = Console.ReadLine();
if (option == "yes")
{
confirmed = true;
}
}
This way if option is anything but yes it will remain in the while loop.
Related
Sorry if the post is duplicated, but I couldn't find any case like mine that is posted here or somewhere else.
I am working on a C# console application that should save the user input and then read it again "Something like a simple sign up and login application".
using System;
using System.IO;
namespace Reader
{
class Program
{
static void Main(string[] args)
{
string filepath = #"C:\myProgramingFiles\password.txt";
StreamReader reader = File.OpenText(filepath);
string line = reader.ReadLine();
Console.WriteLine("Write your username:");
string userInput = Console.ReadLine();
Console.WriteLine("Write your password:");
string password = Console.ReadLine();
Console.WriteLine(userInput);
Console.WriteLine(password);
while(line != null)
{
Console.WriteLine(userInput == line);
Console.WriteLine(password == line);
if (userInput == line)
{
Console.WriteLine("Your username is: " + line);
}
if(password == line)
{
Console.WriteLine("Your password is: " + line);
}
line = reader.ReadLine();
}
reader.Close();
}
}
}
I have this code that reads the data from password.txt, and everything works fine, but when I do the if-else it's first checks if both user inputs are the same as the username, and then it loops again and checks if both user inputs are like the password. Sorry if I couldn't make it clear, you can run this code if you want and mock up the password.txt, and check it.
It is actually a logical and expected result, but the thing is that I don't know how else I should do it. Can you please help me?
I have tried a lot of things that didn't work, and this was my last try, so I know that it is not the best code, but it explains the problem
Let's suppose your password.txt file is like this (which appears to be the case):
password.txt
User1
Pass123
User2
Pass456
etc.
The way your code is written, with that loop you have, if the user enters User1 for the username and Pass123 for the password, the output will be:
Your username is: User1
Your password is: Pass123
BUT if the same user enters User1 and Pass456 the output will be:
Your username is: User1
Your password is: Pass456
Which is obviously undesirable logic.
So what you need is to use your loop to check for the matching username, and only when that condition is met, check for the matching password.
Otherwise you even get results like this, if the user enters Pass123 for the username and Pass456 for the password:
Your username is: Pass123
Your password is: Pass456
This can happen because you are not associating the password with the username. To make them connected you would write the code like this, assuming that username and password are on separate lines:
SOLUTION:
while(line != null)
{
Console.WriteLine(userInput == line);
Console.WriteLine(password == line);
if (userInput == line)
{
// ** CHANGES BEGIN
line = reader.ReadLine(); // get password on next line
if (line == password)
{
Console.WriteLine("Credentials are valid");
}
else
{
Console.WriteLine("Credentials are invalid");
}
break; // no need to continue this loop
}
else {
// Important: skip past password line since the username didnt match
line = reader.ReadLine();
}
// ** CHANGES END
line = reader.ReadLine(); // this is now reading the next username or EOF
}
Put the following into your text file:
hello:world
Put the following into your code:
static void Main(string[] args)
{
string filepath = #"C:\myProgramingFiles\password.txt";
Console.WriteLine("Write your username:");
string username = Console.ReadLine();
Console.WriteLine("Write your password:");
string password = Console.ReadLine();
var lines = File.ReadAllLines(filepath);
var usrpwd = username + ":" + password;
foreach(line in lines)
{
if(usrpwd == line)
Console.WriteLine("Credentials accepted");
}
}
Run the app and type hello as the username and world as the password. Build from there ..
When it comes to saving new data in your text file look at File.AppendAllLines or read all your lines in, add new data in memory and then overwrite the whole file. That's probably most easily arranged by having the data in a list, rather than an array:
var lines = new List<string>(File.ReadAllLines(...));
Then you can lines.Add(...) a user:password pair and write it out again
I'm following a tutorial to create a simple command prompt program to ask for password (console.writeline) and write that the password is authenticated if inputted correctly (console.readline + if statement) - this runs smoothly:
Console.WriteLine("Please Input Your Password:");
var password = Console.ReadLine();
if (password == "secret")
Console.WriteLine("You have been authenticated");
else if (password != "secret")
Console.WriteLine("You have not been authenticated");
The next part of the exercise is to ask for the password to be typed again if it is incorrect. I followed the exercise per the tutorial but upon running the program the program loops the question line after line rather than methodically going through the steps of the code.
var password = "";
while (password !="secret")
Console.WriteLine("Please Input Your Password:");
password = Console.ReadLine();
if (password == "secret")
Console.WriteLine("You have been authenticated");
else if (password != "secret")
Console.WriteLine("You have not been authenticated");
Would be grateful for any advice! thanks!
Your while loop is missing curly blocks {}. when not specifing {} you the while loop only specifies to the next line instead of code block you wanted.
Also, you don't need the else if (password != "secret"). else is enough
var password = "";
while (password !="secret")
{
Console.WriteLine("Please Input Your Password:");
password = Console.ReadLine();
if (password == "secret")
Console.WriteLine("You have been authenticated");
else
Console.WriteLine("You have not been authenticated");
}
So I'm basically trying to make simple login or register console app but I think I can't open the text file because everytime I enter the correct username it closes the app.This is the code which I think should work.
Console.WriteLine("Username:");
string userNameN = Console.ReadLine();
string username = System.IO.File.ReadAllText(#"C:\test.txt");
if (username == userNameN)
{
Console.Clear();
Console.WriteLine("Correct username");
}
else
{
Console.WriteLine("Incorrect username program will close");
System.Threading.Thread.Sleep(1000);
Environment.Exit(0);
}
System.Threading.Thread.Sleep(1000);
It is happening because execution of code is ended. If you want to wait till next input then add Console.ReadLine(); after Console.WriteLine("Correct username");
Now it will wait till next user input.
The following code has preset passwords that the user must enter to continue the code. However, when the set passwords (PASS1-PASS3) are entered, the code goes to the do-while regardless. What do I need to do in order to make the while recognize that the password is correct so that it does not go to the invalid password line?
// Program asks user to enter password
// If password is not "home", "lady" or "mouse"
// the user must re-enter the password
using System;
public class DebugFour1
{
public static void Main(String[] args)
{
const String PASS1 = "home";
const String PASS2 = "lady";
const String PASS3 = "mouse";
String password;
String Password;
Console.Write("Please enter your password ");
password = Console.ReadLine();
do
{
Console.WriteLine("Invalid password enter again: ");
password = Console.ReadLine();
} while (password != PASS1 || password != PASS2 || password != PASS3);
Console.WriteLine("Valid password");
Console.ReadKey();
}
}
You have your logic the wrong way around i.e. do something then check some conditions, whereas you want to check some conditions and then do something. So the following code:
do
{
Console.WriteLine("Invalid password enter again: ");
password = Console.ReadLine();
} while (password != PASS1 || password != PASS2 || password != PASS3);
Should read:
while (password != PASS1 && password != PASS2 && password != PASS3)
{
Console.WriteLine("Invalid password enter again: ");
password = Console.ReadLine();
}
Notice that I also changed the logical ORs || to logical ANDs &&. this is because you want to check if it is not equal to all of them, not just one.
On a side note the variable Password is unused and should be removed as it can lead to typo errors to your used variable password.
Try changing the "||" to "&&".
It will cannot equal all of them at once.
have a menu and submenu system, this submenu contains information about locating a driver's location, I want to be able to do a search within the if statement to find out where said Driver is located. I've attached a link to a screenshot if that helps.
http://imageshack.us/f/14/helpub.png/
I want to be able to press the number 1 (or any other number) and for the application to say the following instead of defaulting back to the depot menu:
Please enter name of driver (in this case Steven)
Then for the application to say:
"Steven is located at Depot A"
Any ideas, tips or suggestions greatly appreciated.
I don't want the coding done for me as this is cheating, I just want a pointing in the right direction
Rafa
Apologies, my first post. Okay what I want to happen is that when I press one in the screen the app will ask me to enter driver's name, driver's name is Kenny. Then I want the app to display "Kenny is located at Depot Liverpool" But I'm not sure how to do this.
Code is as follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Sys
{
private bool isLoggedIn = false;
private List<Depot> myDepots;
public Sys()
{
myDepots = new List<Depot>();
// Hard Code Data
myDepots.Add(new Depot("Liverpool"));
myDepots.Add(new Depot("Saint Helens"));
// Hard Code Data
myDepots[0].AddDriver(new Driver("Kenny", "07"));
myDepots[0].AddDriver(new Driver("Steven", "08"));
myDepots[1].AddDriver(new Driver("Jamie", "23"));
myDepots[1].AddDriver(new Driver("Pepe", "25"));
}
public void Run()
{
do
{
Console.WriteLine("Pick Depot");
for (int index = 0; index < myDepots.Count; index++)
{
Console.WriteLine((index + 1).ToString() + " : " + myDepots[index].GetDepotName());
}
int userChoice = Convert.ToInt32(Console.ReadLine());
string userName = "", passWord = "";
if ((userChoice > 0) && (userChoice < 3))
{
Console.Write("Specify UserName : ");
userName = Console.ReadLine();
Console.Write("Specify PassWord : ");
passWord = Console.ReadLine();
bool diditWork = myDepots[userChoice - 1].CheckPassword(userName, passWord);
if (diditWork)
{
Console.WriteLine("We are Logged On!");
Console.WriteLine(myDepots[userChoice - 1].GetMenu());
string menuInput;
int menuInt;
Console.Write("Please select a menu option: \n1 - Locate a Vehicle \n2 - Locate a Driver \n3 - Set up a Work Schedule \n4 - Exit Menu \n");
menuInput = Console.ReadLine();
menuInt = Int32.Parse(menuInput);
if (menuInt < 0)
{
Console.WriteLine("Your menu selection is invalid, please try again", menuInt);
break;
}
if (menuInt == 1)
{
Console.WriteLine("Please enter model name of vehicle", menuInt);
}
if (menuInt == 2)
{
Console.WriteLine("Please enter driver's surname", menuInt);
This is where I need the option to search a driver by name and then have their location reported back to the user of the app. Basically I need the app to say Kenny is located at Depot A
}
if (menuInt == 3)
{
Console.WriteLine("Please assign driver and vehcile to a new work schedule", menuInt);
}
if (menuInt > 4)
{
Console.WriteLine("Your menu selection is invalid, please try again", menuInt);
}
}
else
{
Console.WriteLine("We are Logged Off!");
}
}
isLoggedIn= false;
} while (true);
}
}
}
Well you can use a case statement with what you have and put whatever code you want in there, though most of us would get upset if it was more than five statements...
Looking at your probable intent though.
I think you want a "Task" class.
e.g.
switch(menuInt)
{
case 1 : Console.WriteLine(GetModelName); break;
case 2 : break; //etc
}
If you want to get a bit more clever, define an interface that defines all the things that a menu option must do to intercat with your menu code. Write a class to do what you want, that implements the interface, then use a factory.
Console.Writeline(MenuItemFactory.CreateItem(menuInt).Response);
Maybe, hard to tell this early on. In fact may be it's a bit too early to start refactoring and you should just beaver away with at least a couple of the options before setting anything in stone.