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

标签 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;
}

最佳答案

即使没有 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,也没有理由使用 default case 中的 if

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

关于c++ - 从 R 控制台获取用户输入:Rcpp 和 std::cin,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45300471/

相关文章:

r - 在 dplyr::funs 的命名参数中,我可以引用其他参数的名称吗?

r - 如何为永远唯一的元素分配一个数字?

r - Y 轴超出 R 中 barplot() 的绘图区域

rcpp 无法在初始化时将 ‘SEXP {aka SEXPREC*}’ 转换为 ‘double’

c++ - Rcpp C/C++ 使用结构和 char*

Rcpp 和 boost : it should work but it does not

c++ - 如何修复无法将参数从 void*[n] 转换为 const void**

c++ - direct.h 文档

c++ - 为什么 GCC 为 0.0/0.0 产生 -nan 和 clang 和 intel 产生 +nan?

c++ - 在函数签名中一起使用 * 和 &