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

C语言函数实现网站欢迎页代码无法正常执行求助

问题排查与修复方案

核心问题点

  • 函数未实际调用:main中的void welcome();、void query();、void ending();是函数声明而非调用语句,必须去掉void写成welcome();这类形式才会执行函数内的打印逻辑。
  • scanf读取换行符干扰:第一个scanf("%c", &name)读取输入字符后,输入时按下的回车(换行符\n)会留在输入缓冲区,第二个scanf("%c", &prob)会直接读取这个换行符,导致程序跳过输入步骤直接执行后续代码。
  • 函数声明拼写错误:原代码中void endig();是拼写错误,应为void ending();,否则会触发未定义函数的编译警告。

修复后的完整代码

#include<stdio.h>
// 正确声明所有自定义函数
void welcome();
void query();
void ending();

void welcome(){
    printf("welcome to our company\n");
}

void query(){
    printf("hello, how can i help you with today?\n");
}

void ending(){
    printf("our sales executive will contact you soon\n");
}

int main()
{
    char name, prob;
    // 调用自定义函数
    welcome();
    printf("please help us with your name\n");
    // 用空格过滤缓冲区的换行符
    scanf(" %c", &name);
    query();
    // 同样用空格过滤换行符
    scanf(" %c", &prob);
    ending();
    return 0;
}

额外优化说明

  • 在scanf的格式符前添加空格" %c",可自动跳过输入缓冲区中的空白字符(换行、空格、制表符等),避免读取到无效的换行符。
  • 所有printf字符串末尾添加\n,确保输出内容及时刷新到终端,避免出现输出不换行的混乱情况。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 11:20:32