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

后端 未结 1 2053
离开以前
离开以前 2020-12-19 12:15

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

1条回答
  •  温柔的废话
    2020-12-19 13:14

    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.

    0 讨论(0)
提交回复
热议问题