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