Everyone knows how to count the characters from STDIN in C. However, when I tried to do that in python3, I find it is a puzzle. (counter.py)
import sys chrCounter = 0 for line in sys.stdin.readline(): chrCounter += len(line) print(chrCounter)
Then I try to test the program by
python3 counter.py < counter.py
The answer is only the length of the first line "import sys". In fact, the program ONLY read the first line from the standard input, and discard the rest of them.
It will be work if I take the place of sys.stdin.readline by sys.stdin.read()
import sys print(len(sys.stdin.read()))
However, it is obviously, that the program is NOT suitable for a large input. Please give me a elegant solution. Thank you!
The gets() function reads a line from the standard input stream stdin and stores it in buffer. The line consists of all characters up to but not including the first new-line character (\n) or EOF. The gets() function then replaces the new-line character, if read, with a null character (\0) before returning the line.
Use fileinput. input() reads through all the lines in the input file names specified in command-line arguments. If no argument is specified, it will read the standard input provided.
It's simpler:
for line in sys.stdin: chrCounter += len(line)
The file-like object sys.stdin
is automatically iterated over line by line; if you call .readline()
on it, you only read the first line (and iterate over that character-by-character); if you call read()
, then you'll read the entire input into a single string and iterate over that character-by.character.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With