In the one answer我找到了这一节,它等待您的输入并打印它,直到您按回车键:

require 'io/console'
require 'io/wait'

loop do
  chars = STDIN.getch
  chars << STDIN.getch while STDIN.ready?       # Process multi-char paste
  break if chars == ?\n
  STDOUT.print chars
end

但是,为了退出loop,我必须按“输入”(新行-cc:>键)两次,或者在它之后按下其他东西。
当我再次尝试执行同一个循环(复制粘贴到同一个pry会话中)时,我得到:
IOError: byte oriented read for character buffered IO

\n引起上述升高,错误。没有这行代码,ruby就不会显示任何错误。
在这两种情况下(带或不带上述行),循环中:
当我按回车键,然后按某个字母(例如“z”)时,就会出现此错误。
在下一个循环中,上面的字母将显示(没有我的输入)。
当我按Enter两次-没有错误,它将退出。
在下一个循环中,当我按下某个字母时,将显示错误。
在上一个循环中,字母将显示
我记得C或C++中有chars << STDIN.getch while STDIN.ready?,这样你就可以清空缓冲区了。我找到了几种方法,并尝试了如下方法:
 loop do
   STDIN.ioflush
   STDOUT.ioflush
   STDOUT.iflush
   STDIN.iflush
   STDOUT.oflush
   STDIN.oflush

   chars = STDIN.getch
   chars << STDIN.getch while STDIN.ready?
   break if chars == ?\n
   STDOUT.print chars
 end

但没用。
如何使用enter和第二个字母&flush解决此行为。我认为两者在某种程度上是相关的。

最佳答案

答案中的代码是我为个人使用而编写的类似highline的库的简化版本。我自己从来没有遇到过这种特殊的错误,但这可能是因为我实际使用的东西略有不同。我的实际代码更像这样:

require 'io/console'
require 'io/wait'

catch(:done) do
  loop do
    chars = STDIN.getch
    chars << STDIN.getch while STDIN.ready?       # Process multi-char paste
    throw :done if ["\r", "\n", "\r\n"].include?(chars)
    STDOUT.print chars
  end
end
STDOUT.print "\n"

我还有一个kill信号处理程序,以防按下ctrl+c(kill process)或ctrl+d(end of input);第一个中断程序,第二个有线响应,就像按下enter一样。
精确的行为可能取决于操作系统(我在osx和freebsd上使用它),因为enter键可以根据操作系统返回任何"\r""\n""\r\n"
\r\n , \r , \n what is the difference between them?

关于ruby - enter&IOError:针对字符缓冲的IO的字节读取,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21456829/

10-12 01:26
查看更多