4

I know we can use Babel to evaluate code block in org-mode. But it seems that Babel can not handle "cin". Like this

int a;std::cin >> a;std::cout << a;

The Babel doesn't ask me to input the value of a, and it output the value 0.

Can Babel handle this problem? Or some other tools can do this.

ernest
  • 197
  • 7
  • Doesn't seem possible; see http://stackoverflow.com/questions/12129038/how-to-pipe-input-to-a-src-block-as-stdin – pdexter May 04 '16 at 17:14

1 Answers1

3

I can think of two different approaches for this. The first approach is to create a file like input.data with content of, say, 4 in the home directory. This will be supplied to std::cin. Then, write the code as follows:

#+begin_src C++ :results output :includes <iostream> :cmdline < ~/input.data
int a;
std::cin >> a;
std::cout << a;
#+end_src

#+RESULTS:
: 4

The second approach, which is more interesting, is to use a little bit of lisp code for interactivity:

#+name: input
#+begin_src elisp
(completing-read "Enter a number: " nil)
#+end_src

#+begin_src C++ :results output :var input=input
#include <iostream>
#include <string>

int main() {
    int a = std::atoi(input);
    std::cout << a;
}
#+end_src

#+RESULTS:
: 3

In this approach, you will be prompted inside emacs to enter a number, which will be used in the C++ code.

Eissa N.
  • 1,695
  • 11
  • 18