vscode c++ 如何使用终端输入输出
时间: 2025-02-15 20:21:25 浏览: 51
### VSCode 中 C++ 程序的终端输入输出配置
#### 配置编译器路径
为了使 VSCode 能够识别并使用安装好的 GCC 编译器,在 `.vscode` 文件夹下创建 `settings.json` 并指定 MinGW 的 gcc/g++ 安装位置[^1]。
```json
{
"terminal.integrated.shell.windows": "C:\\Windows\\System32\\cmd.exe",
"C_Cpp.default.compilerPath": "D:/mingw64/bin/gcc.exe"
}
```
#### 创建简单的 C++ 源码文件
编写一段基础代码用于测试输入输出功能。新建一个名为 `main.cpp` 的源文件:
```cpp
#include <iostream>
using namespace std;
int main(){
string input;
cout << "请输入一些文字: ";
getline(cin, input);
cout << "您刚刚输入的是:" << input << endl;
return 0;
}
```
#### 设置 launch.json 进行调试
在项目根目录下的 .vscode 文件夹内建立或编辑 `launch.json` 来定义启动配置项,允许通过附加参数 `-args` 启动程序时传递命令行参数给应用程序[^2]:
```json
{
"version": "0.2.0",
"configurations": [
{
"name": "(gdb) Launch",
"type": "cppdbg",
"request": "launch",
"program": "${workspaceFolder}/a.exe", // 输出可执行文件的位置
"args": [],
"stopAtEntry": false,
"cwd": "${fileDirname}",
"environment": [],
"externalConsole": true,
"MIMode": "gdb",
"miDebuggerPath": "D:/mingw64/bin/gdb.exe",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
],
"preLaunchTask": "build" // 构建任务名称
}
]
}
```
#### 添加 tasks.json 自动化构建过程
同样位于 `.vscode` 下面增加 `tasks.json` 文件来描述如何调用 g++ 对源代码进行编译:
```json
{
"version": "2.0.0",
"tasks": [
{
"label": "build",
"type": "shell",
"command": "g++.exe",
"args": [
"-g",
"${relativeFile}",
"-o",
"${fileDirname}\\${fileBasenameNoExtension}.exe"
],
"group": {
"kind": "build",
"isDefault": true
},
"problemMatcher": ["$gcc"],
"detail": "Generated task to build the project."
}
]
}
```
当一切准备就绪之后,可以通过点击左侧活动栏中的“运行和调试”图标选择 `(gdb) Launch` 或者直接按 F5 键开始调试会话;也可以简单地右键单击编辑器内的任意地方选择 “Run Code”,此时将会弹出一个新的外部控制台窗口等待用户的键盘输入[^3].
阅读全文
相关推荐


















