从 R 控制台获取用户输入:Rcpp 和 std::cin
Getting user input from R console: Rcpp and std::cin
我一直在做一些练习来学习 c++,并决定将它们集成到 R 中,因为最终我想为 R 函数编写 c++ 后端。 我找不到从 R 控制台检索用户输入的解决方案。虽然有用于打印和返回输出的 Rcpp::Rcout,但 std::cin 似乎没有类似的功能。
#include <Rcpp.h>
// [[Rcpp::export]]
Rcpp::String cola() {
Rcpp::Rcout << "Pick a 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 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;
}
即使没有 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<int>(as_numeric(readline("> ")));
请注意,您的代码中还有另一个错误:您的案例都是失败的,因为您错过了break
;此外,没有理由进行case 0
,并且在默认情况下根本没有理由if
。
哦,最后,不要使用std::endl
,除非你真的需要刷新输出(你只需要在这里这样做一次,最后(;改用'n'
。
相关文章:
- 使用std::multimap迭代器创建std::list
- C++中std::resize(n)和std::shrink_to_fit之间的区别
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 如何导出包含具有"std::unique_ptr"值的"std::map"属性的
- 从持续时间构造std::chrono::system_clock::time_point
- std::具有相同基类的类的变体
- std::mt19937 in Rcpp
- 通过std::shared_ptr使用Rcpp和RcppParallel的线程安全函数指针
- std::Rcpp中的RTYPE值集
- 从 R 控制台获取用户输入:Rcpp 和 std::cin
- C++ Rcpp::接口的接口不适用于返回 std::p air 的函数
- 使用 Rcpp 在 Ubuntu Xenial 上抛出 std::runtime_error 时出现 Segfault
- 检测和省略 rcpp 中 std 向量的 na 值
- 我应该更喜欢 Rcpp::NumericVector 而不是 std::vector 吗?
- 如何将 Rcpp::List 转换为 std::vector<double>
- 创建一个std::shared_ptr对象并将其返回到R端(Rcpp)
- 将Rcpp::CharacterVector转换为std::string
- Rcpp错误:' unique_ptr '不是' std '的成员
- 如何将 std::vector<std::vector> 转换为 Rcpp:<double>:D ataframe 或 Rcpp::NumericMatrix