【问题标题】:CMD shuts down after i input a key我输入一个键后 CMD 关闭
【发布时间】:2016-06-18 15:26:19
【问题描述】:

我使用的是Visual Studio 2015,进入项目文件夹>bin>debug>ConsoleApplication1并打开它,命令提示符打开并说:输入一个数字,任何数字!如果我按任何键命令提示符立即关闭,尝试再次删除和编码但没有用,仍然关闭,但在 Visual Studio 中,当我按 Ctrl + F5 时一切正常。

 class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Type a number, any number!");
        ConsoleKeyInfo keyinfo = Console.ReadKey();

        PrintCalculation10times();

        if (char.IsLetter(keyinfo.KeyChar)) 
        {
            Console.WriteLine("That is not a number, try again!");
        }

        else
        {
            Console.WriteLine("Did you type {0}", keyinfo.KeyChar.ToString());
        }

    }

    static void PrintCalculation()
    {
        Console.WriteLine("Calculating");
    }

    static void PrintCalculation10times()
    {
        for (int counter = 0; counter <= 10; counter++)
        {
            PrintCalculation();
        }
    }

}

【问题讨论】:

  • 那是因为在你输入任何东西之后它会写一行然后没有其他事情可做所以它会关闭。在 main 末尾要求另一个键,它会在关闭之前等待您输入一些内容。

标签: c# .net visual-studio cmd


【解决方案1】:

这应该可以解决问题,请参阅我添加到代码中的注释以了解原因。

static void Main(string[] args)
{
    Console.WriteLine("Type a number, any number!");
    ConsoleKeyInfo keyinfo = Console.ReadKey();

    PrintCalculation10times();

    if (char.IsLetter(keyinfo.KeyChar)) 
    {
        Console.WriteLine("That is not a number, try again!");
    }

    else
    {
        Console.WriteLine("Did you type {0}",keyinfo.KeyChar.ToString());
    }

    //Without the something to do (as you had it) after you enter anything it writes a 
    //line and then has nothing else to do so it closes. Have it do something like this below to fix thisd.
    Console.ReadLine(); //Now it won't close till you enter something.

}

编辑-按要求添加。 @ManoDestra 在我看到他回复之前就给出了答案。

您的循环将运行 11 次(for (int counter = 0; counter

static void PrintCalculation10times()
{
    for (int counter = 0; counter < 10; counter++) //Changed with
    {
        PrintCalculation();
    }
}

【讨论】:

  • 好的,非常感谢,你能告诉我为什么它输入“Canculating” 11 次而不是 10 次
  • 您的循环将运行 11 次(for (int counter = 0; counter
  • @ManoDestra 我用你所说的来回答他的问题,因为我没有更好的方式来表达它。我希望没问题。
  • @Jacobr365 当然。没问题:)
【解决方案2】:

在控制台应用程序中,我通常会在 main() 方法的末尾添加一些类似的内容,以防止程序在我读取输出之前关闭。或者在一个单独的实用程序方法中实现它,您可以从任何控制台应用程序调用它......

while (Console.ReadKey(true).Key != ConsoleKey.Escape)
{
}

如果您愿意,您可以在此之后放置任何其他退出代码。

或者您可以像这样处理 Ctrl-C:How do I trap ctrl-c in a C# console app 并在之后处理它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-03
    • 2016-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-15
    • 2012-04-03
    相关资源
    最近更新 更多