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
Even without Rcpp in the mix, std::cin
is unsuitable for interactive input.
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"];
And then you can use them:
int drink = as(as_numeric(readline("> ")));
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.
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.