sys.stdin.readline() reads without prompt, returning 'nothing in between'

前端 未结 6 2198
被撕碎了的回忆
被撕碎了的回忆 2021-02-12 15:49

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

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

Is supposed to tak

6条回答
  •  星月不相逢
    2021-02-12 16:19

    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.

提交回复
热议问题