Simplest way (assuming you are reading from Console, and user will enter hour then press Enter, then enter minute and press Enter):
static void Main(string[] args)
{
int hour = 0, minute = 0;
const int MAX_NUMBER_OF_DIGITS = 2 ;
Console.Write("Enter Time (HH:MM) = ");
// store cursor position
int cursorLeft = Console.CursorLeft;
int cursorTop = Console.CursorTop;
// use ReadLine, else you will only get 1 character
// i.e. number more than 1 digits will not work
hour = int.Parse(Console.ReadLine());
Console.SetCursorPosition(cursorLeft + MAX_NUMBER_OF_DIGITS , cursorTop);
Console.Write(":");
minute = int.Parse(Console.ReadLine());
// Nitpickers! purposefully not using String.Format,
// or $, since want to keep it simple!
Console.Write("You entered: " + hour + ":" + minute);
}
Output:
Enter Time (HH:MM) = 17:55
You entered: 17:55
Though I would rather recommend you better and less error prone way like this (where user inputs HH:MM and presses Enter a single time i.e. enters a single string including : i.e. colon):
static void Main(string[] args)
{
int hour = 0, minute = 0;
Console.Write("Enter Time in format HH:MM = ");
string enteredNumber = Console.ReadLine();
string[] aryNumbers = enteredNumber.Split(':');
if (aryNumbers.Length != 2)
{
Console.Write("Invalid time entered!");
}
else
{
hour = int.Parse(aryNumbers[0]);
minute = int.Parse(aryNumbers[1]);
// Nitpickers! purposefully not using String.Format,
// or $, since want to keep it simple!
Console.Write("You entered: " + hour + ":" + minute);
}
}
Ahere ?Read()andWrite()work, this looks like it'd be confusing to the user since you're initially prompting for both the hours and minutes, yet your code seems to be expecting it be entered as<Hours><Enter><Minutes><Enter>. I would expect your first call toRead()to fail when the user inputs<Hours>:<Minutes><Enter>, even though that's what your asking them to type. I think you'd be better off reading the hours and minutes as oneStringand just parsing that into its component values.