Vendetta
Vendetta

Reputation: 1

what is the user input type?

i want to write a code that gets input from user and if user gave number, do first operation, if user gave '+' or '-' do second operation, and if user gave a character like'q' or 'e' do operation 3, and etc. is there a way to do this to all data types like bool or double? thanks for your help!

            do
        {
            Console.WriteLine("enter any number to do op 1");//this is an int
            Console.WriteLine("press any letter to do op 2");//this is a char
            Console.WriteLine("press '+' or '-' or '*' or '/' to do op 3"); // i mean any operator symbols (i dont know what type are these symbols!)
            Console.WriteLine("enter any word to do op 4");//this is a string
            Console.ReadLine();
            //here i want something to realize what type is the user input?
            if (//number -----> op 1)
            if (// letter -----> op 2)
            if (//+ or - or * or / -----> op3)
            if (//word -----> op 4)
            if (//user gave a combination of all types(a string that has numbers or symbols and etc) -----> tell him "enter a correct word only using letters")

        } while (true); 

Upvotes: 0

Views: 98

Answers (1)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186813

It seems that you are looking for Finite State Machine:

while (true) {
  Console.WriteLine("enter any number to do op 1");
  Console.WriteLine("press any letter to do op 2");
  Console.WriteLine("press '+' or '-' or '*' or '/' to do op 3"); 
  Console.WriteLine("enter any word to do op 4");
  
  string input = Console.ReadLine();

  if (double.TryParse(input, out double value)) {
    //input represents floating point value (op 1)
    //TODO: put relevant code for op 1 here
  }
  else if (new string[] {"+", '-', "*", "/"}.Contains(input.Trim())) {
    // input stands for opeartion +, -, *, / (op 3)
    char op = input.Trim()[0];
    //TODO: put relevant code for op 3 here 
  }
  else if (input.Length == 1) {
    // input is one letter comand op (op 2)
    char letter = input[0];
    //TODO: put relevant code for op 2 here
  }
  else {
    // input is some string (op 4)
    string word = input;
    //TODO: put relevant code for op 4 here
  }
}

Upvotes: 2

Related Questions