简体   繁体   English

我正在尝试使用ReadLine()或Read()或ReadKey来使用C#读取整数

[英]I'm trying to to use ReadLine(), or Read() or ReadKey to read in integers using C#

I'm new to C# and I'm having some trouble reading some ints out of a Console Window App. 我是C#的新手,从控制台窗口应用程序读取一些整数时遇到了一些麻烦。 What I need to do is have a user enter in some integers and press spacebar and enter more numbers and I need to evaluate the numbers one at a time on the fly without the user pressing Enter. 我需要做的是让用户输入一些整数,然后按空格键,然后输入更多数字,我需要一次动态评估一个数字,而无需用户按Enter。 I then have to do so other stuff with the numbers but that's not an issue. 然后,我必须对数字进行其他处理,但这不是问题。 Should I use Console.Read() or Console.ReadKey(), I know ReadLine() wont do anything until enter is pressed so wont do what I want. 我应该使用Console.Read()还是Console.ReadKey(),我知道ReadLine()在按Enter键之前不会做任何事情,所以不会做我想要的事情。

For your case, ReadKey is more suitable than Read() since the Read terminates when you press the Enter key. 对于您的情况,ReadKey比Read()更合适,因为当您按Enter键时,Read终止。 But ReadKey() is like below: 但是ReadKey()如下所示:

The ReadKey method waits, that is, blocks on the thread issuing the ReadKey method, until a character or function key is pressed. ReadKey方法等待,即,在发出ReadKey方法的线程上阻塞,直到按下字符或功能键为止。 A character or function key can be pressed in combination with one or more Alt, Ctrl, or Shift modifier keys. 可以将一个字符或功能键与一个或多个Alt,Ctrl或Shift修改键组合使用。 However, pressing a modifier key by itself will not cause the ReadKey method to return. 但是,单独按下修饰键不会导致ReadKey方法返回。

Hope This will be helpful for you Difference between Console.Read() and Console.ReadLine()? 希望这对您有所帮助。Console.Read()和Console.ReadLine()之间的区别?

As I understand your question you can use Console.ReadLine() instead of using Console.Read()...Give me further details to update more... 据我了解您的问题,您可以使用Console.ReadLine()而不是Console.Read()...给我更多详细信息以更新更多...

I ended up using a ReadKey(), which seemed to work well. 我最终使用了ReadKey(),它似乎运行良好。 Thanks for the help anyway. 无论如何,谢谢您的帮助。

    numberIntoConsole = Console.ReadKey();
        numberReceived = (int)Char.GetNumericValue(numberIntoConsole.KeyChar);

        if (numberReceived != -1) //checks to see if a spacebar was pressed
        {
            if(numberReceived == lastNumberEntered) //checks if numberReceived is equal to lastNumberEntered
            {
                lastNumberEntered = numberReceived; //make the lastNumberEntered the same as numberReceived
                ++numberChecker; // add to the numberChecker
            } else // else we restart the counter 
            {
                numberChecker = 1;
                lastNumberEntered = numberReceived;
            }
        }

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

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