Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a built-in function in Python 3 like getchar() in C++?

I want to do user input in python which is similar to getchar() function used in c++.

c++ code:

#include<bits/stdc++.h>

using namespace std;
int main()
{
char ch;
while(1){
    ch=getchar();
    if(ch==' ') break;
    cout<<ch;
}
return 0;
}

Input: stack overflow

Output: stack

In the above code, when a space input from the user than the loop breaks. I want to do this in python using getchar() type function as I used in c++ code.

like image 773
miltonbhowmick Avatar asked Feb 16 '18 05:02

miltonbhowmick


3 Answers

Easiest method:

Just use split function

a = input('').split(" ")[0]
print(a)

Using STDIN:

import sys
str = ""
while True:
    c = sys.stdin.read(1) # reads one byte at a time, similar to getchar()
    if c == ' ':
        break
    str += c
print(str)

Using readchar:

Install using pip install readchar

Then use the below code

import readchar
str = ""
while(1):
    c = readchar.readchar()
    if c == " ":
        break
    str += c
print(str)
like image 139
CodeIt Avatar answered Oct 17 '22 08:10

CodeIt


Something like this should do the trick

ans = input().split(' ')[0]
like image 3
Mitch Avatar answered Oct 17 '22 07:10

Mitch


msvcrt provides access to some useful capabilities on Windows platforms.

import msvcrt
str = ""
while True:
    c = msvcrt.getch() # reads one byte at a time, similar to getchar()
    if c == ' ':
        break
    str += c
print(str)

msvcrt is a built-in module, you can read more about in the official documentation.

like image 2
run Avatar answered Oct 17 '22 07:10

run