【问题标题】:Is there a built-in function in Python 3 like getchar() in C++?Python 3 中是否有像 C++ 中的 getchar() 这样的内置函数?
【发布时间】:2018-07-26 23:38:40
【问题描述】:

我想在 python 中进行用户输入,类似于 c++ 中使用的 getchar() 函数。

c++代码:

#include<bits/stdc++.h>

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

输入:堆栈溢出

输出:堆栈

在上面的代码中,当用户输入空格时,循环中断。 我想在 python 中使用我在 c++ 代码中使用的 getchar() 类型函数来执行此操作。

【问题讨论】:

  • stackoverflow.com/questions/510357/… 我见过这个,但我需要python 3中的内置函数方式。为了更清楚我的问题,我给出了c++代码。
  • 那么您的问题标题应该类似于 “Python 3 中是否有像 C++ 中的 getchar() 这样的内置函数?”。无论如何,似乎可能的答案就在那个原始问题中。
  • @milton。见我的answer。第二种方法(使用 STDIN)是使用内置函数。
  • @codelt 非常感谢!它清除了我

标签: python c++ input getchar


【解决方案1】:

最简单的方法:

只需使用拆分功能

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

使用标准输入:

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)

使用 readchar:

使用pip install readchar安装

然后使用下面的代码

import readchar
str = ""
while(1):
    c = readchar.readchar()
    if c == " ":
        break
    str += c
print(str)

【讨论】:

  • 还有一个问题! @Codelt 当我为每个字符输入使用 sys.stdin.read(1) 时它是否存储在缓冲寄存器中?
  • @milton。是的,整个输入都在缓冲区中,我们正在逐字节读取它。
  • 非常感谢你帮助我@Codelt
  • 第一个示例似乎不适用于 Python 3。输入 hello world 会将其拆分为 helloworld,第 0 个元素是 hello。不是一个字符。
  • @FreelanceConsultant 使用输入验证:stack overflow 和输出:stack
【解决方案2】:

这样的事情应该可以解决问题

ans = input().split(' ')[0]

【讨论】:

    【解决方案3】:

    msvcrt 提供对 Windows 平台上一些有用功能的访问。

    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 是一个内置模块,您可以在official documentation 中阅读更多信息。

    【讨论】:

      【解决方案4】:

      Python 3 解决方案:

      a = input('')        # get input from stdin with no prompt
      b = a.split(" ")     # split input into words (by space " " character)
                           # returns a list object containing individual words
      c = b[0]             # first element of list, a single word
      d = c[0]             # first element of word, a single character
      print(d)
      
      #one liner
      c = input('').split(" ")[0][0]
      print(c)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-03-28
        • 2013-04-02
        • 2023-03-06
        • 2015-12-06
        • 1970-01-01
        • 2018-09-08
        • 2011-04-03
        相关资源
        最近更新 更多