2

I am using Visual studio 2015,went to projects folder>bin>debug>ConsoleApplication1 and opened it,Command prompt opened and said: type a number,any number! if i press any key the Command prompt instantly shuts down,tried deleting and coding again but no use,still shuts down,but in Visual studio when i press Ctrl + F5 everything is working.

 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();
        }
    }

}
  • That's because after you enter anything it writes a line and then has nothing else to do so it closes. ask for another key at the end of main and it will wait for you to enter something before closing. – Jacobr365 Mar 04 '16 at 18:50

2 Answers2

2

In console apps, I normally add something along these lines to the end of the main() method to prevent the program from closing before I can read my output. Or implement it in a separate utility method that you can call from any console app...

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

You can place any other exit code after this, if you wish.

Or you can handle Ctrl-C like so: How do I trap ctrl-c in a C# console app and deal with it thereafter.

Community
  • 1
  • 1
ManoDestra
  • 6,325
  • 6
  • 26
  • 50
1

This should fix the problem see the comment i added to code to see why.

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.

}

Edit-By request adding this. The answer was given by @ManoDestra before I even saw he responded.

Your loop will run 11 times (for (int counter = 0; counter <= 10; counter++)). From 0 to 10 inclusive. Make it < 10 or start at 1. – ManoDestra

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