Search code examples
c#parsingconsole-applicationuser-inputconsole-input

eliminate line break after read in C#


using A = System.Console;
public void point()
{
    int hour, minute;
    A.Write("Enter Time (HH:MM) = ");
    hour = A.Read();
    A.Write(":");
    minute = A.Read();
}

I want it to be like

"Enter Time (HH:MM) = 12(hour input):49(minute input)"

but it coming like

"Enter Time (HH:MM) = 12(hour input)
:49(minute input)


Solution

  • 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);
    
        }
    }