在VS Code调试C++程序时,如何实现文件输入重定向?
Hey there! Let me help you fix this—your current launch.json setup isn't working because the < and input.txt are being passed as regular command-line arguments to your program, but in the CMD command a.exe < input.txt, that < is a shell redirection operator, not something your program reads directly.
Here's how to adjust your configuration to get the input redirection working in VS Code's debug mode:
Updated launch.json Setup
First, replace your existing config with this (I'll break down the key changes below):
{ "version": "0.2.0", "configurations": [ { "name": "C++ Launch", "type": "cppdbg", "request": "launch", "program": "${workspaceRoot}/a.exe", "args": [], "stopAtEntry": false, "cwd": "${workspaceRoot}", "environment": [], "externalConsole": true, "miDebuggerPath": "C:\\MinGW\\bin\\gdb.exe", // Double-check this path matches your debugger location "setupCommands": [ { "description": "Enable nicer debug output", "text": "-enable-pretty-printing", "ignoreFailures": true }, { "text": "set startup-with-shell off" } ], "redirectInput": "${workspaceRoot}/input.txt" // This line handles the input redirection } ] }
What Changed & Why:
- Removed
<andinput.txtfromargs: Those aren't arguments your program expects—they're shell syntax, so we don't pass them directly to the executable. - Added
redirectInput: This is the critical line. It tells the debugger to feed the contents ofinput.txtinto your program's standard input, just like the<operator does in CMD. Using${workspaceRoot}ensures it looks for the file in your project's root folder. - Added
set startup-with-shell off: This prevents an extra shell from spawning, which can sometimes mess with the redirection flow.
If you'd rather mimic the exact CMD command behavior (launching via cmd.exe), you can use this alternative config instead:
{ "version": "0.2.0", "configurations": [ { "name": "C++ Launch via CMD", "type": "cppdbg", "request": "launch", "program": "cmd.exe", "args": ["/c", "${workspaceRoot}/a.exe < input.txt"], "stopAtEntry": false, "cwd": "${workspaceRoot}", "environment": [], "externalConsole": true, "miDebuggerPath": "C:\\MinGW\\bin\\gdb.exe" } ] }
This tells VS Code to launch Command Prompt and run your exact original command—super straightforward if you want to replicate the manual terminal behavior.
Either approach should work perfectly for your needs. Just pick the one that feels more intuitive to you!
内容的提问来源于stack exchange,提问作者User12547645

