1

when i run my code, my console suddenly shuts off after a number is entered into the console.

int age;
        Console.WriteLine("How old are you?");

        age = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine("You are {0} years old", age);

can someone help me with this problem? I never get to see the end result because it just shuts off. there are no errors that pop up but it is getting quite frustrating.

Emily
  • 11
  • 1
  • 3
    Add a Console.ReadLine() at the end. The program exits when it does all operations, so just make it wait for user to hit enter. – Ram Kumaran Mar 02 '19 at 20:58
  • 1
    Well, if your program ends (and if you did not start your program from an already open cmd window), it will close the program (console) window. To prevent the program from ending (and thus preventing the window from closing), add a `Console.ReadLine()` as the last line in your main method (i guess). If you are interested in knowing what _Console.ReadLine()_ does, check its documentation... –  Mar 02 '19 at 20:58
  • Try CTRL+F5 when running in Visual Studio. – tkausl Mar 02 '19 at 20:58
  • I prefer `Console.ReadKey()` over `Console.ReadLine()` as it allows the user to hit any key to terminate the program. – Olivier Jacot-Descombes Mar 02 '19 at 21:05
  • Possible duplicate of [Why is the console window closing immediately once displayed my output?](https://stackoverflow.com/questions/8868338/why-is-the-console-window-closing-immediately-once-displayed-my-output) – Wai Ha Lee Mar 03 '19 at 09:32

2 Answers2

0

Add Console.ReadLine() or Console.ReadKey() as your last line.

Stemado
  • 599
  • 5
  • 10
0

When the execution of the program is done, the console windows closes. You have to make a way for a program to keep running so the console window stays open. Usually, this is achieved by adding

Console.ReadKey();

or

Console.ReadLine();

in the end of your code. This way the console is waiting for your input and it stays open. As soon as you hit any key in keyboard (in case of Console.ReadKey()) or Enter key (in case of Console.ReadLine()), execution is done and the console window exits.

elgaspar
  • 458
  • 3
  • 11