【问题标题】:VS code debug console inputVS code 调试控制台输入
【发布时间】:2020-07-31 11:28:42
【问题描述】:

我正在尝试在 MacOS 上使用 VS 代码调试以下 try C++ 程序。它需要用户输入。它只是将两个数字作为输入并返回一个数字列表作为输出的东西。这是我的launch.json

{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "(lldb) Launch",
"type": "cppdbg",
"request": "launch",
"program": "${workspaceFolder}/hello",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceFolder}",
"environment": [],
"externalConsole": true,
"MIMode": "lldb"
}
]
}

当我按 F5 时,确实启动了一个外部终端窗口,但它不执行输出文件“hello”,它只是在我的主文件夹中显示常规提示 ~。如果我只是正常运行文件,一切都会正常运行。 我将发布我正在尝试调试的确切代码作为示例,因为它很简单。


#include <iostream>
using namespace std;

class Calculator
{
private:
    /* data */
public:
    Calculator(/* args */) {}
    ~Calculator() {}
    void PrimeGenerator(int, int);
};


int main(int argc, char *argv[])
{
    cout << "Please enter two numbers: " << endl;
    int x, y;
    cin >> x >> y;
    Calculator c;
    c.PrimeGenerator(x,y);

    cin.ignore();
    cin.get();

    return 0;
}

void Calculator::PrimeGenerator(int x, int y)
{
    for (int i = x; i < y; i++)
    {
        bool prime = true;
        for (int j = 2; j * j <= i; j++)
        {
            if (i % j != 0)
            {
                prime = false;
                break;
            }
        }

        if (prime==true) {
            cout << i << " ";
        }
    }
}

【问题讨论】:

  • 与其描述您的代码,不如以文字形式发布,minimal reproducible example。图片不会粘贴到 IDE 中,指向网站的链接会中断或被防火墙阻止。
  • 完成。带有编译输出和 launch.json 的 hello cpp 应该是可重现的。
  • 要在最后暂停代码,我通常使用std::cout &lt;&lt; "Paused. Press ENTER to continue"; std::cin.ignore(1000000, '\n'); 这会等到按下 ENTER 或输入给定数量的字符。
  • 在这个链接有一个视频,我在 VS 代码上,在 MacOS 上的确切代码,工作得很好 youtu.be/-erXR6k9TeE?t=1280>
  • 我尝试听从您的建议,但并没有太大变化。外部终端打开,但它只是我家中的一个提示,它没有运行我的程序。

标签: c++ macos visual-studio-code vscode-debugger


【解决方案1】:

似乎代码本身没有问题。

您对外部控制台有严格的要求吗?如果没有,可以在终端中手动运行应用程序,然后附加:

{
    "name": "(lldb) Attach",
    "type": "cppdbg",
    "request": "attach",
    "program": "${workspaceFolder}/hello",
    "processId": "${command:pickProcess}",
    "MIMode": "lldb",
    "setupCommands": [
        {
            "description": "Enable pretty-printing for gdb",
            "text": "-enable-pretty-printing",
            "ignoreFailures": true
        }
    ]
}

点击运行按钮后,VSCode 会询问您的 pid:

现在,将能够调试:

【讨论】:

  • 我不一定需要外部控制台,但我肯定需要输入x和y。我需要以某种方式做到这一点。您的建议导致错误:“不允许使用属性控制台”
  • 我没有意识到 console 属性并非对所有语言都可用。因此,我尝试重现这种情况(在 Linux 上,遇到了与您类似的问题)并找到了一种可行的方法。我已经更新了我的答案。
  • 一旦 VS 代码询问 pid 并且我输入它,我的控制台中的进程输出它正在暂停,但它实际上退出了。
  • 但我想我已经找到了崩溃的原因:每当我在数字提示期间调整窗口大小时,都会将几个控制字符发送到流中,因此读取的数字是总垃圾,而 int - 转换将失败。
  • 为什么你认为我没有输出?检查断点的设置位置。当然,当继续使用有效数字时,会打印一些数字(来自素数生成器)。
猜你喜欢
  • 1970-01-01
  • 2022-08-09
  • 1970-01-01
  • 1970-01-01
  • 2021-01-19
  • 2021-04-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多