1

When debugging Rcpp, I usually find myself having to use old-school Rprintf statements to watch variables and program flow (as per the comment from @RomainFrancois on this answer). However, for situations such as large loops, where too much rapid output from Rprintf can quickly disappear over the top of the console, I would like to be able to pause execution until I press a key.

If I try using a std::cin.get() call in the c++ script and running it from Rstudio, the console gets stuck with no obvious way to direct keystrokes to the c++ call that is awaiting them. NB this is an RSudio specific problem - it does not occur when running the same code from a terminal window, which works as expected.

A simple reproducible example:

library(Rcpp)

cppFunction('
void test() {
  for (int i = 0; i < 100; i++) {
    Rprintf(\"i = %i\\n\", i);
    std::cin.get();
  }
}
')

test()

How can I get this to work so I can step through Rcpp functions interactively to debug them?

dww
  • 30,425
  • 5
  • 68
  • 111

1 Answers1

1

OK, I figured out a workaround - which is to use an R function (readline) to read user input, rather than a c++ one. I'd still like to know if there is a way for RStudio to pass input to c++ functions.

cppFunction('
void test(){
  Environment base = Environment("package:base");
  Function readline = base["readline"];
  for (int i = 0; i < 10; i++) {
    Rprintf(\"i = %i\", i);
    readline("");
  }
}
')

test()
dww
  • 30,425
  • 5
  • 68
  • 111