VS Code:标准输入输出的文件重定向

VS Code:标准输入输出的文件重定向


1. 背景

  在进行C/C++编程时,有时需要向.exe中输入数据,但数据又太多或者复杂,特别是调试时需要重复输入多遍,非常麻烦。现希望.exe能够自动输入数据并保存结果。

2. 测试文件

  现VS Code目录有3个文件,分别是:input、main.cpp 、output。main.cpp需要从input中读取数据,计算两个输入值之和,并将结果保存到output中。
input内容:

1 2

main.cpp代码:

#include <iostream>
using namespace std;

//计算两个输入值的和
int main()
{
    int x, y;
    cin >> x >> y;
    cout << x << " + " << y << " = " << x + y << endl;
    return 0;
}

3. 文件重定向

  大多数操作系统都支持文件重定向,它能将标准输入和标准输出与命名文件相关联。
文件重定向的命令一般如下:

***.exe <infile >outfile

cmd命令解析:

// 跳转到main.cpp所在文件夹
cd C:\Users\wyh\Desktop\2  
// 编译main.cpp,生成main.exe
g++ main.cpp -o main.exe
// 文件重定向
main.exe <infile >outfile
// 输出outfile
type outfile

cmd命令重定向结果:
cmd文件重定向结果

  VS Code终端实际上是使用Windows PowerShell。PowerShell支持“>”,不支持“<”。故需要通过“Get-Content”获取输入文件的内容。

Windows PowerShell:
VS Code终端
Windows PowerShell使用“<”报错:
在这里插入图片描述

PowerShell重定向命令:

Get-Content infile | ./***.exe >outfile

PowerShell重定向结果:
PowerShell重定向结果

4. 总结

  1. 文件重定向可以自动读取数据,保存结果。

5. 参考资料

  1. 如何在WindowsPowerShell中重定向标准输入\输出?
发布了77 篇原创文章 · 获赞 25 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_34801642/article/details/103795042