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

坚强是说给别人听的谎言 提交于 2019-11-29 11:04:01

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<int>(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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!