作者:赵乙潘_107 | 来源:互联网 | 2023-01-28 14:29
我一直在做一些练习来学习c ++,并决定将它们集成到R中,因为最终我想为R函数编写c ++后端.我无法找到从R控制台检索用户输入的解决方案.虽然有Rcpp :: Rcout用于打印和返回输出,但似乎没有类似的功能std :: cin ....
#include
// [[Rcpp::export]]
Rcpp::String cola() {
Rcpp::Rcout <<"Pick a drink:" <> 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;
}
Konrad Rudol..
5
即使没有Rcpp,std::cin
也不适合交互式输入.
要将R控制台与Rcpp一起使用,您需要使用R函数(特别是readline
)而不是C++功能.幸运的是,您可以将R对象拉入C++代码:
Environment base = Environment("package:base");
Function readline = base["readline"];
Function as_numeric = base["as.numeric"];
然后你可以使用它们:
int drink = as(as_numeric(readline("> ")));
请注意你的代码中还有另一个错误:你的案例都是错误的,因为你错过了break
; 此外,没有理由拥有case 0
,if
在默认情况下根本没有理由.
哦,最后,std::endl
除非你真的需要刷新输出,否则不要使用(你只需要在这里做一次,最后); 使用'\n'
来代替.
1> Konrad Rudol..:
即使没有Rcpp,std::cin
也不适合交互式输入.
要将R控制台与Rcpp一起使用,您需要使用R函数(特别是readline
)而不是C++功能.幸运的是,您可以将R对象拉入C++代码:
Environment base = Environment("package:base");
Function readline = base["readline"];
Function as_numeric = base["as.numeric"];
然后你可以使用它们:
int drink = as(as_numeric(readline("> ")));
请注意你的代码中还有另一个错误:你的案例都是错误的,因为你错过了break
; 此外,没有理由拥有case 0
,if
在默认情况下根本没有理由.
哦,最后,std::endl
除非你真的需要刷新输出,否则不要使用(你只需要在这里做一次,最后); 使用'\n'
来代替.