while (Cin >> str) An equivalent code in Python

Asked

Viewed 173 times

0

Need to read multiple items without a fixed amount, in c++ just do while (Cin >> str) what would be an equivalent python code? has an answer in English to this same question here in the stack, but the answer is incorrect.

an example in c++:

int main() {

string str;
while (cin >> str) {
    cout<<str;
}

return 0;

}

  • 1

    Axei the vague question, could put an example in c++, to make the analogy with python,

  • friend edited the question.

1 answer

2

In Python, the default entry is visible as an open text file in the object sys.stdin

If the file was redirected from another, the end of file will be detected on sys.stdin - without redirecting, as in the C++ example, the program is forever waiting for new lines.

Thus, a common file method such as readlines() can automatically read all lines of standard input. What it doesn’t do is convert the read content to some type - Python, with all the expressiveness it has, doesn’t have many "magic" in the syntax - you can use a list comprehension or the function map to convert all read lines to integer.

For example:

import sys

dados = map(int, sys.stdin)

Ready - just this - the map asks for an iterable object in the second argument - a text file, when iterated, emits (yields) one line at a time. That line is passed to the flame int, that despises white-space characters - including the newline that comes in the line vinal. In short: dados becomes a generating object that can be used in a for, or may be transformed into a list of dados = list(dados) .

The syntax with list comprehension is:

import sys

dados = [int(linha) for linha in sys.stdin]
  • could you adapt to String please? I’m working with them.

  • For string you don’t need to transform the value - just do dados=list(sys.stdin), or dados = sys.stdin.readlines() . Only if you want to remove end-of-line characters - \n, that needs to be dados = [linha.strip() for linha in sys.stdin()]

Browser other questions tagged

You are not signed in. Login or sign up in order to post.