Reputation: 103
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??/?
Upvotes: 10
Views: 119554
Reputation: 7202
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:
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.
Upvotes: 6
Reputation: 1666
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.
Upvotes: 8
Reputation: 56549
string key = Console.ReadKey().ToString(); //Read what is being pressed
if(key == "") {
Console.WriteLine("User pressed enter!");
return; //stop further execution
}
Upvotes: 15