输入密钥后,CMD关闭

时间:2016-03-04 18:47:02

标签: c# .net visual-studio cmd

我正在使用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();
        }
    }

}

2 个答案:

答案 0 :(得分:2)

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

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

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

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

答案 1 :(得分: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&lt; = 10; counter ++))。从0到10(含)。使它&lt; 10或从1开始。 - ManoDestra

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