How to stop program executing further in C# - c#

string FirstName = Console.ReadLine();
if (FirstName.Length > 12)
{
Console.WriteLine(".......................................");
}
if(FirstName.Length<3)
{
Console.WriteLine("....................");
}
Console.WriteLine("...................");
string SecondName = Console.ReadLine();
if (SecondName.Length > 12)
{
Console.WriteLine(".............................");
}
if(SecondName.Length<3)
{
I want to stop the program if they press enter without putting a value,how to do it??/?

string key = Console.ReadKey().ToString(); //Read what is being pressed
if(key == "") {
Console.WriteLine("User pressed enter!");
return; //stop further execution
}

I think you want to have a non empty string value as an input from console and if input is empty then want to terminate your application. Use following code:
Console.WriteLine("Enter a value: ");
string str = Console.ReadLine();
//If pressed enter here without a value or data, how to stop the program here without
//further execution??
if (string.IsNullOrWhiteSpace(str))
return;
else
{
Console.WriteLine(string.Format("you have entered: '{0}'", str));
Console.Read();
}
If user will enter any kind of empty string or white spaces, the application will be terminated the moment he/she will press enter.

Console.ReadLine() returns a string. If nothing is typed and the human just presses the enter key, we'll get an empty string.
There are a number of ways to test whether a string is "empty" for various definitions of empty. Some common definitions of empty and how to test for them:
non-null and containing no data: myString.Length == 0
null or containing no data: string.IsNullOrEmpty(myString)
null, empty, or just whitespace: string.IsNullOrWhiteSpace(myString)
Environment.Exit() will end the process with the exit code you specify.
Combine one of the tests above with Environment.Exit() (and probably an if) and you can stop the process when there's no "value or data".
Also note, that returning from Main is another way to exit the process.

Related

C# Comparing user input with data from external file C#

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

Looping a password checker in C#?

I'm trying to create a password checker.
My idea was to have a bool return type method with a string parameter which would be the user's input. If the string fulfills all the conditions, the method would return true. Otherwise it should return false and loop from the start (take another input from the user to check the password again).
Problem is, even though I got all the conditions that I wanted to have right, I can't get it to loop every time a condition is false. I've tried to do it with for, etc., but it doesn't seem to work. I assume the problem is in the user input (I'm either putting it somewhere that's wrong or something like that) but at this point I'm out of ideas.
If you have an answer, please explain it to me instead of just giving me some code so I can understand where did I go wrong.
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BeginnerProjects
{
class PasswordCreator
{
static void Main(string[] args)
{
string passLengthReq = "Password length should be 8 symbols or more.";
string passUppercaseReq = "Password should contain at least one uppercase letter.";
string passDigitReq = "Password should contain at least one digit.";
Console.WriteLine("Please insert your desired password, the password has the following requirements:");
Console.WriteLine($"{passLengthReq}\n{passUppercaseReq}\n{passDigitReq}");
string chosenPass = Console.ReadLine();
do
{
IsPassCorrect(chosenPass);
Console.ReadLine();
}
while (IsPassCorrect(chosenPass) == false);
static bool IsPassCorrect(string chosenPass)
{
// Checks for Null
if (string.IsNullOrEmpty(chosenPass))
{
Console.WriteLine("Password is empty!");
return false;
}
// Checks for Length
else if (chosenPass.Length < 8)
{
Console.WriteLine($"Your password is too short, it contains {chosenPass.Length} characters!");
return false;
}
// Checks for Number Present
else if (!chosenPass.Any(char.IsNumber))
{
Console.WriteLine("Error, your password doesn't contain a number!");
return false;
}
// Checks for Decimal Present
else if (chosenPass.Any(char.IsDigit))
{
Console.WriteLine("Error, your password contains a decimal!");
return false;
}
// Checks for Uppercase Letter
else if (!chosenPass.Any(char.IsUpper))
{
Console.WriteLine("Error, your password doesn't contain an uppercase letter!");
return false;
}
else
{
Console.WriteLine("Your password is valid!");
return true;
}
}
}
}
}
Take this part:
string chosenPass = Console.ReadLine();
do
{
IsPassCorrect(chosenPass);
Console.ReadLine();
}
while (IsPassCorrect(chosenPass) == false);
And change it to:
string chosenPass;
do
{
chosenPass = Console.ReadLine();
}
while (IsPassCorrect(chosenPass) == false);
Now the loop will always prompt the user before checking the password, and keep doing so until IsPassCorrect(chosenPass) returns true.
You can simplify IsPassCorrect(chosenPass) == false if desired:
string chosenPass;
do
{
chosenPass = Console.ReadLine();
}
while (!IsPassCorrect(chosenPass));

Program exiting when using String.ToUpper(); on a string that has spaces in it

Let me start off saying that I'm new to C#.
I'm currently in the making of my first command-line application that in it's current state can do two things. One of them is a calculator, for which I need more learning to actually make it work, and the other is a string capitalizer.
I have a string nameCapInput = Console.Readline() that takes in the user input, which then gets analyzed to make sure that no digits are allowed:
using System;
using System.Linq;
namespace First_Console_Project
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("My first ever console application - 2020/2/26\n\n\n");
programSel:
Console.WriteLine("What do you want to do?\n");
Console.WriteLine("1. Calculate Numbers \n2. Capitalize Letters/Strings");
Console.WriteLine("Input your desired action:");
var inputVar = Console.ReadLine();
switch (inputVar)
{
case "1":
//Calculator code goes here
Console.WriteLine("Number 1 succeeded, opening calculator... Stand by");
Console.WriteLine("Calulator Loaded.");
Console.WriteLine("Doesn't work right now. Type \"exit\" to get back to the \"what do you want to do\" page.");
//Code goes here when I have learned the proper methods
calcInput:
var calcInput = Console.ReadLine();
if (calcInput == "exit")
{
goto programSel;
} else
{
Console.WriteLine("Unknown command. Type \"exit\" to get back to the \"what do you want to do\" page.");
goto calcInput;
}
case "2":
Console.WriteLine("Loading string capitalizer...");
Console.WriteLine("Type any string made of letters only without spaces, because if you use spaces, the program will exit. The output will make them all uppercase. Type \"exit\" to get back to the \"what do you want to do\" page.");
inputCap:
string nameCapInput = Console.ReadLine();
bool containsInt = nameCapInput.Any(char.IsDigit);
bool isMadeOfLettersOnly = nameCapInput.All(char.IsLetter);
if (nameCapInput == "exit")
{
goto programSel;
}
else if (containsInt)
{
Console.WriteLine("You can't capitalize numbers. Use letters only. Try again.");
goto inputCap;
}
else if (isMadeOfLettersOnly)
{
string upper = nameCapInput.ToUpper();
Console.WriteLine($"The uppercase version of your entered text is: {upper}");
goto inputCap;
}
break;
}
}
}
}
Now, everything works fine and it capializes everything I put into it except strings with spaces in them. When I type in a string with spaces in it, the program just exits with code 0. I'm not very good at C# yet, so I don't really know where to go from here. Any help is appreciated.
Every time I learn something new in C#, I try to implement it into my projects, so I can actually learn how to implement it to know when and how to use what I learned. This is an example for that.
EDIT: Added the rest of the code.
Thank you all very much. There's two things I have learned here:
goto is a bad habit
I absolutely need to start learning to debug my own code.
The crux of your problem is that you are only checking if the input contains letters (not spaces). An easy fix is to change your LINQ a bit.
bool isMadeOfLettersOnly = nameCapInput.All(c => char.IsLetter(c) || char.IsWhiteSpace(c));
So now input with letters or spaces will be considered valid.
In addition, your use of goto is a very bad idea. Generally there should never be any reason to use goto.
To fix this, use a while loop and a method:
public static void Main()
{
bool exit = false;
do {
exit = ProcessInput();
}
while(!exit);
}
private static bool ProcessInput()
{
string nameCapInput = Console.ReadLine();
bool containsInt = nameCapInput.Any(char.IsDigit);
bool isMadeOfLettersOnly = nameCapInput.All(c => char.IsLetter(c) || char.IsWhiteSpace(c));
if (nameCapInput.Equals("exit", StringComparison.CurrentCultureIgnoreCase))
{
return true; //exiting so return true
}
else if (containsInt)
{
Console.WriteLine("You can't capitalize numbers. Use letters only. Try again.");
}
else if (isMadeOfLettersOnly)
{
string upper = nameCapInput.ToUpper();
Console.WriteLine("The uppercase version of your entered text is: {0}", upper);
}
return false; //no exit, so return false
}
This is just a quick refactor, you could make it better.
Fiddle here
Check the documentation: https://learn.microsoft.com/en-us/dotnet/api/system.char.isletter?view=netframework-4.8
Based on the documentation of the IsLetter function, the space is not included in the return true cases.
I would suggest that you use regular expressions for this or change your last case to
else if (!containsInt)
{
var upper = nameCapInput.ToUpper();
Console.WriteLine($"The uppercase version of your entered text is: {upper}");
goto inputCap;
}
Also check the documentation of goto: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/goto
The goto statement transfers the program control directly to a labeled statement.
A common use of goto is to transfer control to a specific switch-case label or the default label in a switch statement.
The goto statement is also useful to get out of deeply nested loops.
You are not in any such case, so you shouldn't use it.

Why does the console close after my last input?

My program allows the user to put in 20 prices and to display the average of those values. Why does the console close after I enter my last input? Below is the code I'm running:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace machineproblem4
{
class Program
{
static void Main(string[] args)
{
int sum = 0;
double average = 0;
Console.WriteLine("\t\t\t INPUT PRICES \n");
int[] price = new int[20];
Console.WriteLine("\t\t\t Please enter 20 prices \n");
for (int ctr = 0; ctr < 20; ctr++)
{
Console.Write("Enter price {0} : ", ctr + 1);
price[ctr] = Convert.ToInt32(Console.ReadLine());
}
// [...calculate sum...]
//average
Console.WriteLine("\n----------------------------");
Console.WriteLine("||average of the prices||");
average = sum / 20;
Console.WriteLine("average of the prices: {0}", average);
//more code that outputs statistics about the inputs
//exit
//Edit: This is what fixed my problem
Console.WriteLine("press any key to exit ..");
Console.ReadKey();
}
}
}
use Console.Readline();
Read(), ReadLine() and ReadKey() are basically static methods, and they comes under the Console class. That's why we use these methods like:
Console.Read():-- method accept the String and return the integer.
Console.ReadLine():--method accept the String and return string .
Console.ReadKey():--method accept the Character and also return Character.
That's why we mostly use the Console.ReadKey() method, for come back to source code from output window .
Because when we only press the character we directly come on source code. If you will use the Console.Read() and Console.ReadLine method then
you need to press Enter, come back to the source code rather then any character.
You can place a Console.Read() at the last statement. You can also place a breakpoint at your last statement
Generally, it is not a good idea to wait for user input from a console application. This is okay for debugging, but not definitely for release.
So, first find out if your application is in debug or release config using
private static bool IsDebug()
{
object[] customAttributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(DebuggableAttribute), false);
if ((customAttributes != null) && (customAttributes.Length == 1))
{
DebuggableAttribute attribute = customAttributes[0] as DebuggableAttribute;
return (attribute.IsJITOptimizerDisabled && attribute.IsJITTrackingEnabled);
}
return false;
}
Then use,
if (IsDebug())
Console.Readline();
This eliminates the need to edit the code for different build configurations. Alternative is to put a breakpoint and debug the console app, as suggested by #Erwin
Put:
Console.Readline();
at the end of your main function, so it waits until you press enter before it closes.
None of the previous answers actually directly answer the question of why this is happening. The reason why the console is closing after your last input is that the rest of the code runs very quickly and when it reaches the end of your program, the console closes. This is correct behavior and should be expected when running a console application. As the other answers have stated, you can work around this by requiring a final input before closing the console, but that is all it is, a work around.
If you were to output to a text file rather than just the console, you would see that all of the output is generated as you would expect. The console output and close is just too fast for you to see it without some sort of pause in the code.
Additionally, a solution that has not been mentioned yet is to run the project from Visual Studio without debugging, which will automatically output "Press any key to continue..." when it finishes processing before closing the console. That way you can see what it is outputting without extraneous code that you wouldn't want to have in production code.

Is it possible to read unknown number of lines from console in C#?

There is a function, which can read a single line from the console input (Console.ReadLine()), but I wish to read or some arbitrary number of lines, which is unknown at compile time.
Of course it is. Just use just read a single line (using ReadLine() or whatever else you please) at a time within either a for loop (if you know at the beginning of reading how many lines you need) or within a while loop (if you want to stop reading when you reach EOF or a certain input).
EDIT:
Sure:
while ((line = Console.ReadLine()) != null) {
// Do whatever you want here with line
}
Some of the other answers here loop until a null line is encountered while others expect the user to type something special like "EXIT". Keep in mind that reading from the console could be either a person typing or a redirected input file:
myprog.exe < somefile.txt
In the case of redirected input Console.ReadLine() would return null when it hits the end of the file. In the case of a user running the program interactively they'd have to know to how to enter the end of file character (Ctrl+Z followed by enter or F6 followed by enter). If it is an interactive user you might need to let them know how to signal the end of input.
simple example:
class Program
{
static void Main()
{
CountLinesInFile("test.txt"); // sample input in file format
}
static long CountLinesInFile(string f)
{
long count = 0;
using (StreamReader r = new StreamReader(f))
{
string line;
while ((line = r.ReadLine()) != null)
{
count++;
}
}
return count;
}
}
The best thing to do here is use a loop:
string input;
Console.WriteLine("Input your text (type EXIT to terminate): ");
input = Console.ReadLine();
while (input.ToUpper() != "EXIT")
{
// do something with input
Console.WriteLine("Input your text(type EXIT to terminate): ");
input = Console.ReadLine();
}
Or you could do something like this:
string input;
do
{
Console.WriteLine("Input your text (type EXIT to terminate): ");
input = Console.ReadLine();
if (input.ToUpper() != "EXIT")
{
// do something with the input
}
} while (input.ToUpper() != "EXIT");

Categories

Resources