How to restrict the user input to five digits?

后端 未结 6 1308
生来不讨喜
生来不讨喜 2021-01-26 11:11

I\'m trying to restrict the user to only input 5 digits into the console for C#. I have my code error check the user, but for some reason after I type let\'s say...6 digits, the

6条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-26 11:36

    It can be done this way...

                Console.WriteLine("Enter the the zip code of the contact.");
                var temp = Console.ReadLine();
                string zipcode = string.Empty;
                while (temp.Length != 5)
                {
                    Console.WriteLine("Error. Zip code is not 5 digits. Please enter a valid number.");
                    if (temp.Length == 5)
                    {
                        zipcode = temp;
                        break;
                    }
                    else
                    {
                        temp = Console.ReadLine();
                    }
                }
                Console.Write(zipcode);
    

提交回复
热议问题