简体   繁体   English

如何在C#中从控制台读取很长的输入?

[英]How to read very long input from console in C#?

I need to load veeeery long line from console in C#, up to 65000 chars. 我需要在C#中从控制台加载veeeery long line,最多65000个字符。 Console.ReadLine itself has a limit of 254 chars(+2 for escape sequences), but I can use this: Console.ReadLine本身的限制为254个字符(转义序列为+2),但我可以使用:

static string ReadLine()
{
    Stream inputStream = Console.OpenStandardInput(READLINE_BUFFER_SIZE);
    byte[] bytes = new byte[READLINE_BUFFER_SIZE];
    int outputLength = inputStream.Read(bytes, 0, READLINE_BUFFER_SIZE);
    Console.WriteLine(outputLength);
    char[] chars = Encoding.UTF7.GetChars(bytes, 0, outputLength);
    return new string(chars);
}

...to overcome that limit, for up to 8190 chars(+2 for escape sequences) - unfortunately I need to enter WAY bigger line, and when READLINE_BUFFER_SIZE is set to anything bigger than 8192, error "Not enough storage is available to process this command" shows up in VS. ...克服这个限制,最多8190个字符(转义序列+2) - 不幸的是我需要输入WAY更大的行,当READLINE_BUFFER_SIZE设置为大于8192的任何值时,错误“没有足够的存储空间可供处理这个命令“显示在VS. Buffer should be set to 65536. I've tried a couple of solutions to do that, yet I'm still learning and none exceeded either 1022 or 8190 chars, how can I increase that limit to 65536? 缓冲区应该设置为65536.我已经尝试了几个解决方案来做到这一点,但我还在学习并且没有超过1022或8190个字符,我怎么能将该限制增加到65536? Thanks in advance. 提前致谢。

try Console.Read with StringBuilder 使用StringBuilder尝试Console.Read

        StringBuilder sb =new StringBuilder();
        while (true) {
            char ch = Convert.ToChar(Console.Read());
            sb.Append(ch);
            if (ch=='\n') {
                break;
            }
        }

You have to add following line of code in your main() method: 您必须在main()方法中添加以下代码行:

byte[] inputBuffer = new byte[4096];
                Stream inputStream = Console.OpenStandardInput(inputBuffer.Length);
                Console.SetIn(new StreamReader(inputStream, Console.InputEncoding, false, inputBuffer.Length));

Then you can use Console.ReadLine(); 然后你可以使用Console.ReadLine(); to read long user input. 阅读长用户输入。

I agree with Manmay, that seems to work for me, and I also attempt to keep the default stdin so I can restore it afterwards: 我同意Manmay,这似乎对我有用,我也尝试保留默认的标准输入,以便我可以在之后恢复它:

        if (dbModelStrPathname == @"con" ||
            dbModelStrPathname == @"con:")
        {
            var stdin = Console.In;

            var inputBuffer = new byte[262144];
            var inputStream = Console.OpenStandardInput(inputBuffer.Length);
            Console.SetIn(new StreamReader(inputStream, Console.InputEncoding, false, inputBuffer.Length));

            dbModelStr = Console.In.ReadLine();

            Console.SetIn(stdin);
        }
        else
        {
            dbModelStr = File.ReadAllText(dbModelStrPathname);
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM