【发布时间】:2021-04-25 16:39:36
【问题描述】:
我正在使用 VS Code IDE 在 macOS 上学习 C 语言。
下面是我尝试运行的 C 代码。
#include <stdio.h>
int main(void)
{
int number_from_user;
/* Get number from user */
printf("Please enter month number: ");
scanf("%d", &number_from_user);
/* Print month name */
switch (number_from_user)
{
case 1:
printf("January");
break;
case 2:
printf("February");
break;
case 3:
printf("March");
break;
case 4:
printf("April");
break;
case 5:
printf("May");
break;
case 6:
printf("June");
break;
case 7:
printf("July");
break;
case 8:
printf("August");
break;
case 9:
printf("September");
break;
case 10:
printf("October");
break;
case 11:
printf("November");
break;
case 12:
printf("December");
break;
default:
printf("Not a month");
printf("Please run the program again");
break;
}
}
下面是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": "gcc - Build and debug active file",
"type": "cppdbg",
"request": "launch",
"program": "${fileDirname}/${fileBasenameNoExtension}",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceFolder}",
"environment": [],
"externalConsole": true,
"MIMode": "lldb",
"preLaunchTask": "C/C++: gcc build active file"
}
]
}
我面临的问题是,要使scanf 函数工作,我需要将externalConsole 设置为true。不幸的是,当我运行代码时,它确实打开了终端,但它打开了一个空白终端,实际上并没有运行代码。
我做错了什么,我该如何解决?
【问题讨论】:
-
代码本身很好,虽然有点笨拙和幼稚。尝试将
printf("Please enter month number: ")替换为printf("Please enter month number:\n")。它有效,那么这是一个行缓冲问题。如果不是,则问题出在您的环境中。 -
添加
\n并不能解决问题。绝对是我的环境有问题。 -
一个简单的“Hello World”程序可以工作吗?
-
当我将
externalConsole设置为false 时,printf工作正常,但scanf显然不行,因为 VSCode 的调试控制台无法接收用户输入。所以我将externalConsole设置为true,当我这样做时,没有任何效果。 -
由于实际的 C 代码与问题无关,如果您简化代码以获得minimal reproducible example,则更有可能回答您的问题。
标签: c macos visual-studio-code vscode-debugger