You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MacOS下VSCode+Code Runner运行C代码输入无响应问题求助

问题解决:MacOS下VSCode+Code Runner运行C代码输入无响应

问题描述

我是编程新手,在MacOS系统上使用VSCode并安装了Code Runner插件,运行C代码时遇到异常:程序提示输入数值,但按下回车键后没有任何反应,必须重新运行代码才会输出结果。

原代码

// my code 
#include <stdio.h> 

int main(){ 
    int no_eggs;
    printf("The total number of eggs gotten is: ");
    scanf("%i\n", &no_eggs);

    double dozen = no_eggs/12.0;
    printf("This gives %f dozen eggs\n", dozen);
    return 0;
}

终端输出

kaye@mis-MacBook-Pro-455 ~ % cd "/Users/kaye/Desktop/" && gcc *.c -o hello && "/Users/kaye/Desktop/"hello
The total number of eggs gotten is: 30
cd "/Users/kaye/Desktop/" && gcc *.c -o hello && "/Users/kaye/Desktop/"hello
This gives 2.500000 dozen eggs

问题原因

问题出在scanf的格式字符串里的\n。scanf解析格式字符串时,\n会匹配任意数量的空白字符(包括回车、空格、制表符),这意味着输入数值按下回车后,scanf会持续等待非空白字符输入才会结束,导致程序卡住无法继续执行。

修复后的代码

#include <stdio.h> 

int main(){ 
    int no_eggs;
    printf("The total number of eggs gotten is: ");
    scanf("%i", &no_eggs); // 移除格式字符串中的\n

    double dozen = no_eggs/12.0;
    printf("This gives %f dozen eggs\n", dozen);
    return 0;
}

验证效果

修改后重新运行代码,输入数值按下回车,程序会立即计算并输出结果,无需重新运行即可正常执行。

内容的提问来源于stack exchange,提问作者beginnercoder

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 14:17:03