【问题标题】:与 C++ 中 python 的 Input("msg") 类似的功能
【发布时间】:2022-01-23 15:34:44
【问题描述】:

我希望在 c++ 中创建这个函数,input("x = ");,有点像在 python 中,这个函数打印 () 中的消息和期望的输入。它可以采用 only bool,str,int,double。我想过像这样进行结构输入

struct input {
 
 std::string str;
 int num;
 double dub;
 bool boolean;
 input(const char *s) {
   std::cout << s;
   std::cin >> ### ; //here is my problem 
 }
};

但这就是我所能得到的。我尝试了模板,但仍然无法弄清楚。

提取输入应该不难,我会弄清楚的,现在我只想看看如何在结构中获取我的数据。

【问题讨论】:

  • 由于您可能从输入中读取的所有内容最初都是一个字符串,您如何知道要提取哪种类型?每个输入都适合一个字符串,每个整数字符串适合一个双精度。你必须有一个优先级或某种标记来决定如何解释输入

标签: c++ c++11 templates iostream


【解决方案1】:

由于类型系统根本不同,通常将 Python 翻译成 C++ 是很困难的。但是,这不是问题。来自documentation

如果提示参数存在,则将其写入标准输出,不带尾随换行符。然后该函数从输入中读取一行,将其转换为字符串(去除尾随的换行符),然后返回。读取 EOF 时,会引发 EOFError。

Python 的 input 不进行任何转换。它只返回一个字符串。可以启用EOF 异常,但它需要一些样板文件才能在实际引发异常时重置流异常设置。它可以在 RAII 类的帮助下完成,其唯一目的是重置流之前的异常设置,无论函数是返回还是抛出。

struct eof_exception_enabled {
    std::istream & inp;
    std::ios::iostate old;
    eof_exception_enabled(std::istream& inp) : inp(inp), old(inp.exceptions()) {
        inp.exceptions(old | std::ios::eofbit);
    }
    ~eof_exception_enabled() {
        inp.exceptions(old);
    }
};


std::string input(std::string prompt = "") {
    std::cout << prompt;
    std::string res;
    auto inp = eof_exception_enabled{std::cin};
    std::getline(inp.inp, res);
    return res;
}

实际上,将输入流也传递给input 会更惯用,以便可以使用不同的流。不确定这对于提示用户并通常从标准输入读取的函数有多大意义。


如果您想启用转换,您可以使用利用字符串流进行转换的函数模板:

template <typename T>
T from_string(const std::string& str) {
    std::stringstream ss{str};
    T t;
    ss >> t;
    return t;
}

用法是

auto age = from_string<int>( input("enter your age:"));

但是,正确处理由于意外输入引起的错误需要更多的时间。当从流中提取整数类型失败时,from_string 只会返回 0。不过,现在我们正在讨论转换,这在 Python 中也不是由 input 完成的。

【讨论】:

  • 为什么是if (prompt.size() &gt; 0)?只需无条件打印,它总是有效的。至于EOF错误,可以使用std::cin.exceptions()查询并(临时)告诉流在EOF上抛出异常。
  • @KonradRudolph 我首先错过了“没有训练换行符”,因此if。我不熟悉输入流的异常,但幸运的是我最近看到了一个关于 Bjarnes Io_guard 的问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-27
  • 2013-04-23
  • 1970-01-01
  • 2011-07-15
  • 2011-12-17
  • 1970-01-01
相关资源
最近更新 更多