我正在尝试在 Rcpp 中打开一个文件函数,所以我需要文件名作为 char* 或 std::string。
到目前为止,我已经尝试了以下方法:
#include <Rcpp.h>
#include <boost/algorithm/string.hpp>
#include <fstream>
#include <string>
RcppExport SEXP readData(SEXP f1) {
Rcpp::CharacterVector ff(f1);
std::string fname = Rcpp::as(ff);
std::ifstream fi;
fi.open(fname.c_str(),std::ios::in);
std::string line;
fi >> line;
Rcpp::CharacterVector rline = Rcpp::wrap(line);
return rline;
}
但显然,as
不适用于 Rcpp::CharacterVector
,因为我收到编译时错误。
foo.cpp: In function 'SEXPREC* readData(SEXPREC*)':
foo.cpp:8: error: no matching function for call to 'as(Rcpp::CharacterVector&)'
make: *** [foo.o] Error 1
有没有一种简单的方法可以从参数中获取字符串或以某种方式从 Rcpp 函数参数中打开文件?
最佳答案
Rcpp::as()
需要 SEXP
作为输入,而不是 Rcpp::CharacterVector
。尝试将 f1
参数直接传递给 Rcpp::as()
,例如:
std::string fname = Rcpp::as(f1);
或者:
std::string fname = Rcpp::as<std::string>(f1);
关于c++ - 将 Rcpp::CharacterVector 转换为 std::string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8421250/