Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

User input commands in Console application

I would like my console application to have commands like user types /help and console writes help. I would like it to use switch like:

switch (command)
{
    case "/help":
        Console.WriteLine("This should be help.");
        break;

    case "/version":
        Console.WriteLine("This should be version.");
        break;

    default:
        Console.WriteLine("Unknown Command " + command);
        break;
}

How can I achieve this? Thanks in advance.

like image 445
TheNeosrb Avatar asked Dec 20 '22 02:12

TheNeosrb


1 Answers

Based on your comment to errata's answer, it appears you want to keep looping until you're told not to do so, instead of getting input from the command line at startup. If that's the case, you need to loop outside the switch to keep things running. Here's a quick sample based on what you wrote above:

namespace ConsoleApplicationCSharp1
{
  class Program
  {
    static void Main(string[] args)
    {
        string command;
        bool quitNow = false;
        while(!quitNow)
        {
           command = Console.ReadLine();
           switch (command)
           {
              case "/help":
                Console.WriteLine("This should be help.");
                 break;

               case "/version":
                 Console.WriteLine("This should be version.");
                 break;

                case "/quit":
                  quitNow = true;
                  break;

                default:
                  Console.WriteLine("Unknown Command " + command);
                  break;
           }
        }
     }
  }
}
like image 61
Ken White Avatar answered Jan 02 '23 10:01

Ken White