从R控制台获取用户输入:Rcpp和std :: cin [英] Getting user input from R console: Rcpp and std::cin

查看:60
本文介绍了从R控制台获取用户输入:Rcpp和std :: cin的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在做一些练习来学习c ++,并决定将它们集成到R中,因为最终我想为R函数编写c ++后端。
我在寻找从R控制台检索用户输入的解决方案时遇到了麻烦。

I have been doing some exercises to learn c++ and decided to integrate them into R since ultimately I want to write c++ backends for R functions. I am having trouble finding a solution to retrieve user input from the R console. While there is Rcpp::Rcout for printing and returning output, there doesn't seem to be a similar funciton for 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 不适合交互式输入。

Even without Rcpp in the mix, std::cin is unsuitable for interactive input.

要在Rcpp中使用R控制台,您需要使用R函数(尤其是 readline )而不是C ++函数。幸运的是,您可以将R对象放入C ++代码中:

To use the R console with Rcpp, you need to use R functions (in particular, readline) instead of C++ functionality. Luckily you can pull R objects into your C++ code:

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

然后您可以使用它们:

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

请注意,您的代码中还有另一个错误:由于您缺少休息;此外,没有理由将 case 0 设置为零,也没有理由在默认情况下将 if 设置为$

Beware that there's another error in your code: your cases are all fall-through since you are missing the break; furthermore, there’s no reason to have a case 0, and there’s no reason at all for the if in the default case.

哦,最后,除非真正需要刷新输出,否则不要使用 std :: endl (最后您只需要在这里做一次);请使用’\n’

Oh, and finally, don’t use std::endl unless you actually need to flush the output (and you only need to do this once here, at the end); use '\n' instead.

这篇关于从R控制台获取用户输入:Rcpp和std :: cin的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆