Skip to content

[API Proposal]: Console: .ReadBool, .ReadInt, .ReadLong and so on #64621

Open

Description

Background and motivation

Many lovers of C# like me used console class for programming competitions and faced to a problem like 'TimeLimit' or 'OutOfMemory' verdicts. It is related to very slowly reading from console because console reads whole line in RAM (like in Python), it is their main problem at all in programming compretitions.
I want to extend console class with 'read' methods (like 'cin' in C++), which will significantly optimize reading from the console and increase the popularity of using the language in competitions.

API Proposal

namespace System
{
    public static class Console
    {
        public static string ReadToken(params char[] skipChars)
        {
            var hashSet = skipChars.ToHashSet();
            var c = (char) In.Read();
            while (hashSet.Contains(c))
            {
                c = (char) In.Read();
            }
        
            var sb = new StringBuilder();
            while (!hashSet.Contains(c))
            {
                sb.Append(c);
                c = (char) In.Read();
            }

            return sb.ToString();
        }

        public static string ReadToken() => ReadToken(' ', '\n', '\r');
        public static bool ReadBool() => bool.Parse(ReadToken());
        public static decimal ReadDecimal() => decimal.Parse(ReadToken());
        public static double ReadDouble() => double.Parse(ReadToken());
        public static float ReadFloat() => float.Parse(ReadToken());
        public static int ReadInt() => int.Parse(ReadToken());
        public static long ReadLong() => long.Parse(ReadToken());
    }
}

API Usage

var n = Console.ReadLong();
var arr = new int[n];
for (var i = 0; i < n; i++)
{
    arr[i] = Console.ReadInt();
}

Alternative Designs

No response

Risks

No response

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions