Question

Why does a Rcpp function with a \n line break sent to Rcpp::Rcout not compile?

This works

cppFunction('void testing() {Rcout<<"hello"<<std::endl;}')
testing()
# hello

but this doesn't

cppFunction('void testing() {Rcout<<"hello\n";}')
Was it helpful?

Solution

R's string escaping is getting in your way. Try:

cppFunction('void testing() {Rcout<<"hello\\n";}')

Note the double \\. Rather than transferring a literal new-line to the generated C++ script, you want to send the characters \n themselves -- hence, you need to escape the \.

To avoid issues like this, you should prefer using the attributes interface -- see Rcpp-attributes.

Note that this error becomes more obvious if you try running cppFunction('void testing() {Rcout<<"hello\n";}', verbose=TRUE) -- you can see the generated script has a literal newline rather than the \n characters.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top