如何在VSCode编译运行C++文件时传递input.txt参数
在VSCode中让C++程序自动读取input.txt输入
要实现编译后自动用input.txt作为程序输入,有两种常用方法,根据你的使用习惯选择:
方法一:修改tasks.json,新增运行任务
在现有tasks.json中添加一个依赖编译任务的运行任务,通过shell重定向让程序读取input.txt:
{ "tasks": [ { "type": "cppbuild", "label": "C/C++: g++ build active file", "command": "/usr/bin/g++", "args": [ "-fdiagnostics-color=always", "-g", "-std=c++17", "-Wshadow", "-Wall", "${file}", "-o", "${fileDirname}/${fileBasenameNoExtension}" ], "options": { "cwd": "${fileDirname}" }, "problemMatcher": ["$gcc"], "group": { "kind": "build", "isDefault": true }, "detail": "Task generated by Debugger." }, { "label": "Run C++ with input.txt", "type": "shell", "command": "${fileDirname}/${fileBasenameNoExtension} < input.txt", "dependsOn": "C/C++: g++ build active file", "options": { "cwd": "${fileDirname}" }, "problemMatcher": [] } ], "version": "2.0.0" }
使用方式:按Ctrl+Shift+B,在弹出的任务列表中选择「Run C++ with input.txt」,程序会先编译再自动读取input.txt的内容作为输入。
方法二:配置launch.json(适合用调试按钮运行)
如果你习惯点击右上角的运行/调试按钮,创建或修改.vscode/launch.json文件,通过配置标准输入路径实现自动化:
{ "version": "0.2.0", "configurations": [ { "name": "C/C++: g++ build and run with input.txt", "type": "cppdbg", "request": "launch", "program": "${fileDirname}/${fileBasenameNoExtension}", "stopAtEntry": false, "cwd": "${fileDirname}", "environment": [], "externalConsole": false, "MIMode": "gdb", "preLaunchTask": "C/C++: g++ build active file", "setupCommands": [ { "description": "Enable pretty-printing for gdb", "text": "-enable-pretty-printing", "ignoreFailures": true } ], // 配置标准输入为input.txt "stdio": { "stdin": "${fileDirname}/input.txt" } } ] }
使用方式:点击右上角的运行按钮,程序会自动完成编译并读取input.txt的内容,无需手动输入。
注意事项
确保input.txt文件放在当前C++代码所在的目录下,否则程序无法找到输入文件。
内容的提问来源于stack exchange,提问作者Quicksvolex
相关产品推荐
相关产品推荐

