从R控制台获取用户输入:Rcpp和std :: cin

时间:2017-07-25 10:22:53

标签: c++ r rcpp

我一直在做一些练习来学习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;
}

1 个答案:

答案 0 :(得分:5)

即使没有混合使用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'