C# 如何在C语言中停止程序的进一步执行# string FirstName=Console.ReadLine(); 如果(FirstName.Length>12) { 控制台写入线(……); } 如果(FirstName.Length 12) { 控制台写入线(…………); } if(SecondName.Length
C# 如何在C语言中停止程序的进一步执行# string FirstName=Console.ReadLine(); 如果(FirstName.Length>12) { 控制台写入线(……); } 如果(FirstName.Length 12) { 控制台写入线(…………); } if(SecondName.Length,c#,C#,Console.ReadLine()返回一个字符串。如果没有键入任何内容,而用户只需按enter键,则会得到一个空字符串 对于各种空定义,有多种方法可以测试字符串是否为“空”。一些常见的空定义以及如何测试: 非空且不包含数据:myString.Length==0 null或不包含数据:string.IsNullOrEmpty(myString) null、空或仅空白:string.IsNullOrWhiteSpace(myString) 将使用指定的退出代码结束进程 将上面的一个测试与Env
Console.ReadLine()
返回一个字符串。如果没有键入任何内容,而用户只需按enter键,则会得到一个空字符串
对于各种空定义,有多种方法可以测试字符串是否为“空”。一些常见的空定义以及如何测试:
- 非空且不包含数据:
myString.Length==0
或不包含数据:null
string.IsNullOrEmpty(myString)
、空或仅空白:null
string.IsNullOrWhiteSpace(myString)
Environment.Exit()
(如果,可能还有一个)结合起来,当没有“值或数据”时,您可以停止该过程
另外请注意,从Main
返回是退出流程的另一种方式。我认为您希望从控制台输入一个非空字符串值,如果输入为空,则希望终止应用程序。使用以下代码:
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)
{
string key = Console.ReadKey().ToString(); //Read what is being pressed
if(key == "") {
Console.WriteLine("User pressed enter!");
return; //stop further execution
}
如果用户输入任何类型的空字符串或空格,应用程序将在他/她按enter键时终止。此问题可能重复,而您的其他问题表明您对C#完全陌生。请先阅读一些教程。阅读更多答案:我的意思是如果“enter”如果他们在输入值后按enter键怎么办?我的意思是说,只有在没有任何值的情况下按enter键怎么办?如果他们输入一个值并按enter键怎么办???@user2996625如果您添加了一些值,上面的if语句将不会执行。即使输入了一些值,您想停止吗?
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();
}