Getting user input from the R console: Rcpp and std :: cin

I’m doing some exercises for learning C ++ and decided to integrate them into R, because in the end I want to write C ++ backends for R functions. I am having trouble finding a solution to extract user input from console R. As long as there is Rcpp :: Rcout for printing and returning output, it looks like there is no similar function 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;
}
+4
source share
1 answer

Even without Rcpp in the mix, std::cinnot suitable for interactive input.

R Rcpp, R ( , readline) ++. , R ++:

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'.

+4

Source: https://habr.com/ru/post/1682207/


All Articles