4
我一直在做一些练习来学习C++,并决定将它们集成到R中,因为最终我想为R函数编写C++后端。 我无法找到解决方案来从R控制台检索用户输入。虽然有RCPP :: RCOUT打印和返回输出,似乎没有成为的std :: CIN的类似功能可按....从R控制台获取用户输入:Rcpp和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;
}
谢谢,它确实有帮助。 实际上,'case 0'和'if'语句的原因是如果drink是除1-5之外的任何数字,则发送错误。由于'switch'不能处理我选择使用'if'的范围。除非我错了。 – JulianS
@JulianS我明白了,但我在答案中所说的话仍然存在:在默认情况下,'case 0'和'if'只是多余的。删除它们,你会得到所需的行为。事实上,它会更好,因为它也可以处理负数,你当前的代码完全忽略。 –
噢,我明白你的意思了。 另外我需要改变: 'INT饮料= as_numeric(readline的( “> ”));' 到: 'INT饮料= RCPP ::如(as_integer(readline的(“>”)))' –
JulianS