Search code examples
emacsorg-modebabeljs

Is it possible to use Babel in org-mode to evaluate code block which "cin" is involved in?


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.


Solution

  • 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.