I have a function that executes the following (among other things):
userinput = stdin.readline()
betAmount = int(userinput)
Is supposed to tak
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()
.
As an example, given 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)
... if I run this script as follows (I've typed in the 234
):
C:\>python rd.py
234
x= 2
userinput= 34
betAmount= 34
... so the 2
is being picked up first, leaving the 34
and the trailing newline character to be picked up by the readline()
.
I'd suggest fixing the problem by using readline()
rather than read()
under most circumstances.