Gujrathi Siddhant
Gujrathi Siddhant

Reputation: 27

How to compile and run a C++ program with input from input.txt and output to output.txt in VSCode?

I'm using Visual Studio Code (VSCode) to work on a C++ project and I want to automate the process of compiling my C++ code and running it with input redirected from a file (input.txt) and the output saved to another file (output.txt).

I've set up a tasks.json file in VSCode to build the code and run the program, but when I try to execute the task, I encounter issues with input/output redirection. I need a solution that allows me to compile the code and handle input and output files properly.

I configured tasks.json to compile the C++ file with g++ and run the executable with input/output redirection. The task should compile hash.cpp, redirect input from input.txt, and save the output to output.txt

enter image description here

i go to the terminal -> configure tasks ->create tasks.json from template -> and then update the tasks.json file with below tasks.json

tasks.json

{
    "version": "2.0.0",
    "tasks": [
      {
        "label": "Compile and run",
        "type": "shell",
        "command": "",
        "args": [
          "copy",
          "\"${file}\"",
          "${workspaceFolder}\\jspwTest.cpp",
          "&&",
          "g++",
          "jspwTest.cpp",
          "-o",
          "jspwTest",
          "&&",
          "jspwTest",
          "<",
          "input.txt",
          ">",
          "output.txt",
          "&&",
          "del",
          "jspwTest.exe",
          "&&",
          "del",
          "jspwTest.cpp"
        ],
        "presentation": {
          "reveal": "never"
        },
        "group": {
          "kind": "build",
          "isDefault": true,
        },
        "problemMatcher": {
          "owner": "cpp",
          "fileLocation": [
            "relative",
            "${workspaceRoot}"
          ],
          "pattern": {
            "regexp": "^(.*):(\\d+):(\\d+):\\s+(warning|error):\\s+(.*)$",
            "file": 1,
            "line": 2,
            "column": 3,
            "severity": 4,
            "message": 5
          }
        }
      }
    ]
  }

I want when i click to run "ctrl + shift + b" it should read the input from input.txt and write the output in output.txt.
But it is giving me error and compilation i.e, .exe file is also not generating.

Upvotes: 1

Views: 95

Answers (0)

Related Questions