是否可以在 org-mode 中使用 Babel 来评估 "cin" 涉及的代码块?
Is it possible to use Babel in org-mode to evaluate code block which "cin" is involved in?
我知道我们可以使用 Babel 来评估 org-mode 中的代码块。但是Babel好像处理不了"cin"。像这样
int a;std::cin >> a;std::cout << a;
Babel没有让我输入a的值,它输出的是0值。
Babel 能解决这个问题吗?或者其他一些工具可以做到这一点。
我可以想到两种不同的方法。第一种方法是在主目录中创建一个类似于 input.data
的文件,其内容为 4
。这将提供给 std::cin
。然后,编写如下代码:
#+begin_src C++ :results output :includes <iostream> :cmdline < ~/input.data
int a;
std::cin >> a;
std::cout << a;
#+end_src
#+RESULTS:
: 4
第二种方法更有趣,是使用一些 lisp
代码进行交互:
#+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
在这种方法中,系统会在 emacs 中提示您输入一个数字,该数字将在 C++
代码中使用。
我知道我们可以使用 Babel 来评估 org-mode 中的代码块。但是Babel好像处理不了"cin"。像这样
int a;std::cin >> a;std::cout << a;
Babel没有让我输入a的值,它输出的是0值。
Babel 能解决这个问题吗?或者其他一些工具可以做到这一点。
我可以想到两种不同的方法。第一种方法是在主目录中创建一个类似于 input.data
的文件,其内容为 4
。这将提供给 std::cin
。然后,编写如下代码:
#+begin_src C++ :results output :includes <iostream> :cmdline < ~/input.data
int a;
std::cin >> a;
std::cout << a;
#+end_src
#+RESULTS:
: 4
第二种方法更有趣,是使用一些 lisp
代码进行交互:
#+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
在这种方法中,系统会在 emacs 中提示您输入一个数字,该数字将在 C++
代码中使用。