Insights

BOJ Problem 11718: No input values, and No EOFError?

funczun 2024. 11. 22. 11:22
sys.stdin.readline() returns an empty string!
import sys

while True:
    try:
        userInput = sys.stdin.readline().strip()
        print(userInput)
    except:
        break

 EOFError(End of File) means the end of the file, or the end of input. The input() function raises an EOFError at the end of the file, but sys.stdin.readline() returns an empty str, so it does not raise an EOFError. This can lead to incorrect handling due to output overflow.

 

 You can simplify the above code like this:

while True:
    try:
        print(input())
    except:
        break

 

Using sys.stdin.readlines() is also a good approach!
import sys

userInput = sys.stdin.readlines()

for i in userInput:
    print(i.strip())

 Using sys.stdin.readlines() instead of input() can reduce the time taken. However, both sys.stdin.readline() and sys.stdin.readlines() include a newline character(\n) at the end, so it’s essential to use strip() to remove the newline character.

 The difference between sys.stdin.readline() and sys.stdin.readlines() is whether you read one line of input or read all input at once and store each line as an element in a list. In the case of sys.stdin.readlines(), when the user presses Enter, that line is read and added to the list, but it waits until it receives a signal indicating the end of input, so you need to press Ctrl + Z to end the program input.