如何在Sublime Text中创建支持C语言用户输入的构建系统?
在Sublime Text中创建支持用户输入的C语言构建系统(无需终端/Terminus)
Sublime Text默认的构建输出面板不支持直接输入,要实现无终端的输入交互,我们可以通过自定义构建系统结合Python脚本调用程序,用Sublime的输入面板获取用户输入并传递给程序。
步骤1:创建自定义构建系统
- 打开Sublime Text,依次点击
Tools>Build System>New Build System... - 删除默认模板内容,粘贴以下配置:
{ "cmd": ["gcc", "-std=c11", "$file", "-o", "$file_base_name"], "file_regex": "^(..[^:]*):([0-9]+):?([0-9]+)?:? (.*)$", "working_dir": "${file_path}", "selector": "source.c", "variants": [ { "name": "Run with Input", "cmd": ["python3", "-c", "import subprocess, sys, sublime; input_text = sublime.active_window().show_input_panel('Enter input:', '', None, None, None); proc = subprocess.Popen([sys.argv[1]], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True); stdout, stderr = proc.communicate(input=input_text); print(stdout); print(stderr, file=sys.stderr)", "$file_base_name"], "shell": true } ] }
- 保存文件为
C_Input.sublime-build,保存路径选择默认的Packages/User目录即可。
步骤2:编译并运行带输入的C程序
- 编写测试用的C代码(比如
test.c):
#include <stdio.h> int main() { char name[50]; printf("Enter your name: "); scanf("%s", name); printf("Hello, %s!\n", name); return 0; }
- 编译代码:按下
Ctrl+B(Windows/Linux)或Cmd+B(macOS),完成编译后会生成同名可执行文件。 - 运行并输入:按下
Ctrl+Shift+B(Windows/Linux)或Cmd+Shift+B(macOS),选择C_Input - Run with Input。此时会弹出输入面板,输入内容后回车,输出面板就会显示程序的运行结果。
注意事项
- 确保系统已安装
gcc和python3(Windows系统替换为python),且两者都在系统环境变量的PATH中。 - 多段输入可以在输入面板中用换行符分隔,程序会按顺序读取。
内容的提问来源于stack exchange,提问作者Anshul Pratap Lakra
相关产品推荐
相关产品推荐

