0

I am trying to make a dialog in C# console... and I try to make it answer the users's question:

"tell me the date and time"

or something like that. This is my code:

resp3 = Console.ReadLine();
if (resp3 == "tell me the curent date and time")
{
    Console.Write(string.Format("{0:HH:mm:ss tt}", DateTime.Now));
}

After it writes the answer to the console, it just closes.

Hogan
  • 69,564
  • 10
  • 76
  • 117
doddo26
  • 13
  • 4
  • Your code works for me. What is the problem? – rory.ap Nov 15 '16 at 18:23
  • 2
    Consoles close when their execution is complete, you need a blocking call to stop it from disappearing such as `Console.ReadLine();` – Rudi Visser Nov 15 '16 at 18:23
  • 1
    Keep in mind: `tell me the curent date and time` and `Tell me the curent date and time` are **NOT** equal. – Joel Coehoorn Nov 15 '16 at 18:25
  • Please ask a question when using this site. I for one would greatly appreciate something like, "Why does my program close at the end?", or, "How do I keep a console application open after it's done executing everything?", rather than, "After it writes the answer to the console, it just closes.", which just sounds like random facts: "I like pineapples. Today is November 15th. I wrote a console app, it just closes at the end". – Quantic Nov 15 '16 at 19:25

3 Answers3

3

The code is finished, to continue you need to add this:

Console.ReadLine();
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
  • yhea that is logic :D my problem was... "the consol is not showing me the date and it close after some seconds sorry for bad english..: – doddo26 Nov 19 '16 at 13:02
0

You could make the code a bit cleaner and versatile:

var phrase = "...";
if(String.Compare(Console.ReadLine(), phrase, true) == 0)
     Console.WriteLine(DateTime.Now.ToString("0:HH:mm:ss tt");

Console.ReadLine();

The comparison will deviate case sensitivity, so it becomes case insensitive. Also, you can do your format directly to the end of DateTime when you utilize the ToString. It has all the same formatting as String.Format. Also the Console.ReadLine is required at the end as Sajeetharan denoted.

Greg
  • 11,302
  • 2
  • 48
  • 79
0

Keeping the basic structure, just add Console.ReadLine() at the end

   resp3 = Console.ReadLine();
   if (resp3 == "tell me the curent date and time")
   {
      Console.Write(string.Format("{0:HH:mm:ss tt}", DateTime.Now));
   }
   Console.ReadLine();

This makes sure that the program pause at the end whether or not the correct input was entered.

BahJiy
  • 66
  • 8
  • yea.. i think in the original code is a problem... i mean.. when i try this code in a diffrent project it works... if i use it in the original code it crashes... thank u ;) – doddo26 Nov 19 '16 at 13:07