【问题标题】:Getting user input from R console: Rcpp and std::cin从 R 控制台获取用户输入:Rcpp 和 std::cin
【发布时间】:2017-07-25 10:22:53
【问题描述】:

我一直在做一些练习来学习 c++,并决定将它们集成到 R 中,因为最终我想为 R 函数编写 c++ 后端。 我无法找到从 R 控制台检索用户输入的解决方案。虽然有 Rcpp::Rcout 用于打印和返回输出,但 std::cin.... 似乎没有类似的功能。

#include <Rcpp.h>
// [[Rcpp::export]]
Rcpp::String cola() {
  Rcpp::Rcout << "Pick a drink:" << std::endl << "1 - Espresso" << std::endl << "2 - Americano" << std::endl << "3 - Latte" << std::endl << "4 - Cafe dopio" << 
std::endl << "5 - Tea" << std::endl;
  int drink;
  std::cin >> drink;
  std::string out;
  switch(drink) {
  case 1: out = "Here is your Espresso";
  case 2: out = "Here is your Americano";
  case 3: out = "Here is your Latte";
  case 4: out = "Here is your Cafe dopio";
  case 5: out = "Here is your Tea";
  case 0: out = "Error. Choice was not valid, here is your money back.";
    break;
  default:
    if(drink > 5) {out = "Error. Choice was not valid, here is your money back.";}
  }
  return out;
}

【问题讨论】:

    标签: c++ r rcpp


    【解决方案1】:

    即使没有 Rcpp,std::cin 也不适合交互式输入。

    要将 R 控制台与 Rcpp 一起使用,您需要使用 R 函数(特别是 readline)而不是 C++ 功能。幸运的是,您可以将 R 对象拉入您的 C++ 代码中:

    Environment base = Environment("package:base");
    Function readline = base["readline"];
    Function as_numeric = base["as.numeric"];
    

    然后你就可以使用它们了:

    int drink = as<int>(as_numeric(readline("> ")));
    

    请注意您的代码中还有另一个错误:您的案例全部失败,因为您缺少 break;此外,没有理由有case 0,在默认情况下也没有理由使用if

    哦,最后,不要使用std::endl,除非你真的需要刷新输出(你只需要在最后做一次);请改用'\n'

    【讨论】:

    • 谢谢,真的很有帮助。实际上,case 0if 语句的原因是如果drink 是1-5 以外的任何数字,则发送错误。由于switch 无法处理我选择使用if 的范围。除非我弄错了。
    • @JulianS 我理解,但我在答案中所说的仍然有效:您的case 0 和默认情况下的if 只是多余的。删除它们,您将获得所需的行为。事实上,它会更好,因为它还可以处理负数,而您当前的代码完全忽略了它。
    • 哦,对了……我明白你的意思了。我还需要将:int drink = as_numeric(readline("&gt; ")); 更改为:int drink = Rcpp::as&lt;int&gt;(as_integer(readline("&gt; ")))
    猜你喜欢
    • 2011-06-12
    • 1970-01-01
    • 1970-01-01
    • 2013-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-08
    • 1970-01-01
    相关资源
    最近更新 更多