首页 > 解决方案 > 编译时从 input.txt 在 VS 代码终端中自动输入

问题描述

通常我们需要在运行任何有 std::cin 的文件后输入输入,如下面的 c++ 代码

    int M,N;
    cin>>M>>N;
    int i,a[M],b[N];
    for(i=0;i<M;i++)
    {
        cin>>a[i];
    }
    for(i=0;i<N;i++)
    {
        cin>>b[i];
    }
    Solution ob;
    cout<<ob.countPairs(a, b, M, N)<<endl;

我只是不喜欢每次都输入相同的大输入。所以我想为相同的输入自动化这个过程,比如我将输入保存在一个名为 input.txt 的文件中,运行该文件后,它应该从 input.txt 获取输入并输出结果。Ofc 将输入保存到剪贴板是一种方法,但我可能想复制其他内容,而编码和复制粘贴本身又是一项小工作。

我在 ubuntu 中使用 VS 代码编辑器,并使用 coderunner 扩展在终端中运行代码。

标签: c++visual-studio-codeinputautovscode-code-runner

解决方案


脚本

将您的长输入写入文件,input.txt

the quick brown fox jumped over the lazy dog

使用 bash 脚本script.sh

# Compile your program, ie:
clang++ source.cpp -o application

# Check compilation succeeded
if [[ $? -ne 0 ]]; then
    echo "compilation failed"
    exit 1
fi

# Pipe your input into the application
cat input.txt | ./application 

最后,调用您的脚本:

$ bash script.sh

读书:


推荐阅读