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?
Asked Answered
C

8

43

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.

Consanguineous answered 1/5, 2016 at 9:7 Comment(4)
did you find the answer to that question?Kernel
@Kernel no I couldn't find the answer anywhere. Recently I have not checked. But at that, I came into a conclusion, that this has to be supported from the plugin level, that's what running the code.Consanguineous
Actually I was able to find the answer: github.com/thecoderok/cpp-vscode/blob/master/.vscode/… . Use "terminal": "integrated"Kernel
Looks to be an open issue at the moment: github.com/microsoft/vscode-cpptools/issues/5497Supraorbital
H
48

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

Harbert answered 15/4, 2018 at 20:19 Comment(5)
this worked for me, thanks... I also was running it from the actual terminal by navigating to the file path, but this is much easier @HarbertCassaundracassava
This didn't work for me. I tried to add the suggested line in settings.json. The terminal output goes to the Debug console still.Hotchkiss
@Hotchkiss just check that you have added this setting at the root level. Means on a level where code-runner.executorMapByFileExtension exists.Hide
For whomsoever who cannot find it in latest versions. Go to help> all commands > type preferences> select preferences: language-specific settings > select c++ > paste the above code after 3rd line, it will work.Tread
for the record, the question being asked here does not state that they are using that extension, while it states it is using others.Babettebabeuf
P
19

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. :)

Pyromagnetic answered 11/10, 2020 at 10:45 Comment(2)
I don't see it in mine (Mac OS)Watersoak
@Watersoak I didn't manage to solve the way they said on MacOS. However installing the Code Runner extension by Jun Han was enough to solve it.Quittance
G
17

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.

Gastronomy answered 2/8, 2021 at 15:48 Comment(1)
So it's not possible unless we add a specific 3rd party extension??Hereabout
B
3

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.

Babettebabeuf answered 25/10, 2023 at 6:19 Comment(0)
M
1

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

Migratory answered 7/4, 2020 at 7:6 Comment(0)
T
1

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

Trouveur answered 25/1, 2022 at 15:5 Comment(0)
C
0

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

Coo answered 27/11, 2019 at 1:37 Comment(0)
C
0

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

Constraint answered 20/3 at 13:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.