sys.stdin.readline() 在没有提示的情况下读取,返回“中间没有任何内容" [英] sys.stdin.readline() reads without prompt, returning 'nothing in between'

查看:40
本文介绍了sys.stdin.readline() 在没有提示的情况下读取,返回“中间没有任何内容"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个执行以下操作的函数(除其他外):

I have a function that executes the following (among other things):

userinput = stdin.readline()
betAmount = int(userinput)

应该从 stdin 中获取输入整数作为字符串并将其转换为整数.

Is supposed to take input integer from stdin as a string and convert it to an integer.

然而,当我调用该函数时,它返回一个换行符(它甚至不等我输入任何内容).

When I call the function, however, it returns a single newline character (it doesn't even wait for me to input anything).

在程序的早期,我以以下形式获得一些输入:

Earlier in the program I get some input in the form of:

stdin.read(1)

捕获单个字符.

会不会跟这个有关?我是否以某种方式在 stdin 的下一行写了一个换行符?

Could this have something to do with it? Am I somehow writing a newline character to the next line of stdin?

我该如何解决这个问题?

How can I fix this?

推荐答案

stdin.read(1)stdin 读取一个字符.如果在那一点要读取多个字符(例如,读入的一个字符后面的换行符),则该字符或多个字符仍将在缓冲区中等待下一个 read()readline().

stdin.read(1) reads one character from stdin. If there was more than one character to be read at that point (e.g. the newline that followed the one character that was read in) then that character or characters will still be in the buffer waiting for the next read() or readline().

举个例子,给定rd.py:

from sys import stdin

x = stdin.read(1)
userinput = stdin.readline()
betAmount = int(userinput)
print ("x=",x)
print ("userinput=",userinput)
print ("betAmount=",betAmount)

...如果我按如下方式运行这个脚本(我输入了 234):

... if I run this script as follows (I've typed in the 234):

C:\>python rd.py
234
x= 2
userinput= 34

betAmount= 34

...所以 2 首先被拾取,而 34 和尾随的换行符由 readline()<拾取/代码>.

... so the 2 is being picked up first, leaving the 34 and the trailing newline character to be picked up by the readline().

我建议在大多数情况下使用 readline() 而不是 read() 来解决问题.

I'd suggest fixing the problem by using readline() rather than read() under most circumstances.

这篇关于sys.stdin.readline() 在没有提示的情况下读取,返回“中间没有任何内容"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆