Arnab Das
Arnab Das

Reputation: 3728

How can I write to the standard input of a C/C++ program I'm running/debugging in VS Code with the C/C++ extension?

Currently, I'm trying to write C/C++ program in Visual Studio code. For this I've installed two extensions: C/C++ & C++ Intellisense

As per the documentation, the debugging facility is not available for windows. I've been able to build and run the code with the following tasks:

{
    "version": "0.1.0",
    "command": "cmd",
    "isShellCommand": true,
    "args": [
        "/C"
    ],
    "tasks": [
        {
            "taskName": "Makefile",
            "suppressTaskName": true,
            // Make this the default build command.
            "isBuildCommand": true,
            // Show the output window only if unrecognized errors occur.
            "showOutput": "always",
            // No args
            "args": [
                "C:/Programs/cygwin/bin/make.exe",
                "all"
            ],
            // Use the standard less compilation problem matcher.
            "problemMatcher": {
                "owner": "cpp",
                "fileLocation": [
                    "relative",
                    "${workspaceRoot}"
                ],
                "pattern": {
                    "regexp": "^(.*):(\\d+):(\\d+):\\s+(warning|error):\\s+(.*)$",
                    "file": 1,
                    "line": 2,
                    "column": 3,
                    "severity": 4,
                    "message": 5
                }
            }
        },
        {
            "taskName": "Run",
            "suppressTaskName": true,
            "isTestCommand": true,
            "args": [
                "helloworld"
            ]
        }
    ]
}

and one simple Makefile:

all: clean helloworld

helloworld: helloworld.cpp
    C:/Programs/cygwin/bin/g++ helloworld.cpp -o helloworld

clean:
    C:/Programs/cygwin/bin/rm -rf helloworld

But, the problem arises, when the programs needs some user input while running. Suppose for this very familiar helloworld program.

# include <iostream>

using namespace std;

int main ()
{
  int name;

  cin >> name;

  cout << "Hello, " << name << "!!!" << endl;

  return 0;
}

Can you please help me to get the user input at run time. There is a work-around to pass the input as command line arguments. But, that is not possible for programs with complex flows.

Upvotes: 47

Views: 189094

Answers (8)

n a
n a

Reputation: 143

Below is a demonstration of the issue. enter image description here

My Mac version is macOS Monterey version 12.4. I have tried all the methods mentioned above, even the vscode official instruction (https://code.visualstudio.com/docs/cpp/config-clang-mac). So far, none of them worked at my end.

Here I want to share a simple way how it worked out finally. No configuration is required. As the compilation is successful, we just need to start another terminal and run the executable file there. See below for the details. enter image description here

Upvotes: 0

starball
starball

Reputation: 50225

Sigh. Almost every single answer here is about the Code Runner extension, and this question post very clearly states that it's using the C/C++ extension and not Code Runner, which honestly doesn't have much value in my eyes ever since the ms-vscode.cpptools extension added its own run button and supports debugging.

If you have no idea what I mean when I say "task" or "launch config", I'd encourage you to first take a look at the docs on tasks, the docs for launch configs, and the docs for configuring C++ debugging.

If you're on macOS

I think you need to use a cppdbg launch config and set its externalConsole property to true if you use "request": "launch", or use attachment ("request": "attach"). See this snippet of that property's docs:

When set to false, the output can be seen in VS Code's debugConsole. Due to limitations within lldb-mi, integratedTerminal support is not available.

I don't think writing to the program's standard input is supported through the debug console.

If you're on Windows or Linux

(disclaimer: I've tested this info on Linux but not on Windows. feedback is welcome. Maybe if I have the time and motivation I'll test on Windows too)

If you didn't configure a build task or launch config

Then clicking the run/debug button (it's shaped like a play button and has a dropdown menu to switch between "Run C/C++ File" or "Debug C/C++" file) that the C/C++ extension provides in the action button strip at the top right of the workbench (same effect if you run C/C++: Run C/C++ File/C/C++: Debug C/C++ File in the command palette) will prompt you to "Select a debug configuration", at which point it will provide a list of builtin/detected launch configurations which can be used for basic debugging purposes like this:

C/C++: <compiler> build and debug active file (preLaunchTask: C/C++ <compiler> build active file)
Detected Task: (compiler: <compiler path>)

Take your pick of which compiler you want to use. The program will be run (with a debugger if you chose to run with debugging), and two integrated terminal instances will be created/used- one for the build task (that "preLaunchTask" thing) named something like "<compiler> build active file", and another for running your program named something like "cppdbg: <executable name>". That terminal for running your program is where you can write things for the program's standard input stream.

If you configure a default build task and don't have a launch config

Then the run button and corresponding commands will just use that build task and a generic launch config that fits it. You very very probably want the build task to not hardcode for specific file names unless you want the run button or the corresponding commands to only ever run/debug one specific file regardless of what file is currently focused/active.

The same applies: Check the Terminal Panel. There should be a terminal instance there waiting for you.

If you use a launch configuration

Pretty much the same answer as the above. If you have a default build task, the first launch configuration with that task as its preLaunchTask is used. If there is no default build task, or the default build task is defined in the user-level tasks.json file, you'll be prompted which launch config to use.

Go to the integrated terminal panel. There'll be a terminal instance there where you can write to the standard input of your running program- that is, unless:

  • you used file redirection in the launch config to redirect a file to the standard input of the program (Ex. "args": ["<", "input_file.in"] in the launch config),

  • or you put "externalConsole": true in your launch config, in which case an external console will be launched. setting, which I'm not sure if is used here.-->

If you're using CMake Tools

Same goes (it integrates with the C/C++ extension). Check the Terminal Panel. You should see an instance with a title like "cppdbg: <target>". If you run with debugging, you can also do things like file redirection and externalConsole with the cmake.debugConfig setting.

Upvotes: 4

Nafis Ahmad
Nafis Ahmad

Reputation: 47

go to "settings", and search for "code-runner: Run in terminal" and check it. That's how i fixed it.

Upvotes: 1

Mubtasim Fuad
Mubtasim Fuad

Reputation: 359

Make sure you have code runner installed on your VS code.

From top select: File > Preferences > Settings

Search for code runner in settings and check the box:

code runner settings

By default it remains unchecked. You have to enable it to run your preferred languages in terminal.

Upvotes: 19

傅继晗
傅继晗

Reputation: 1137

if you encounter the same problem as me that the integratedTerminal cannot read input from the user as below hanging(env. windows 10) enter image description here

my solution was to replace cygwin's gdb and g ++ with mingw64's.

then the input/output are normal enter image description here

Upvotes: 0

kaxi1993
kaxi1993

Reputation: 4700

Go to Code -> Preferences -> Settings and add custom settings:

{
   "code-runner.runInTerminal": true
}

Finally run your c++ code and you will be able to enter values in console

Upvotes: 51

Tanish Sarmah
Tanish Sarmah

Reputation: 486

Go to settings (ctrl+,) -> Search settings -> : Code-runner : Run in terminal - Check this and you will be able to run the code directly in the terminal which takes input. :)

Upvotes: 20

c0deManiac
c0deManiac

Reputation: 95

As an added convenience, you can also supply inputs from a comment into the integrated terminal.

Example:

# include <iostream>
using namespace std;
int main ()
{
  int name;
  cin >> name;
  cout << "Hello, " << name << "!!!" << endl;
  return 0;
}
/*input
123
*/

Extension Link --
Comment Input: https://marketplace.visualstudio.com/items?itemName=virresh.cinp

Note: This extension depends on code-runner, another extension that can run scripts for almost all languages (and you can specify custom build options as well)

Disclaimer: I'm the author of this extension

Upvotes: 1

Related Questions