c++ - Getting user input from R console: Rcpp and std::cin -
i have been doing exercises learn c++ , decided integrate them r since want write c++ backends r functions. having trouble finding solution retrieve user input r console. while there rcpp::rcout printing , returning output, there doesn't seem similar funciton std::cin....
#include <rcpp.h> // [[rcpp::export]] rcpp::string cola() { rcpp::rcout << "pick 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 espresso"; case 2: out = "here americano"; case 3: out = "here latte"; case 4: out = "here cafe dopio"; case 5: out = "here tea"; case 0: out = "error. choice not valid, here money back."; break; default: if(drink > 5) {out = "error. choice not valid, here money back.";} } return out; }
even without rcpp in mix, std::cin
unsuitable interactive input.
to use r console rcpp, need use r functions (in particular, readline
) instead of c++ functionality. luckily can pull r objects c++ code:
environment base = environment("package:base"); function readline = base["readline"]; function as_numeric = base["as.numeric"];
and can use them:
int drink = as<int>(as_numeric(readline("> ")));
beware there's error in code: cases fall-through since missing break
; furthermore, there’s no reason have case 0
, , there’s no reason @ if
in default case.
oh, , finally, don’t use std::endl
unless need flush output (and need once here, @ end); use '\n'
instead.
Comments
Post a Comment