Sherryr丶 2023-11-02 23:54 采纳率: 0%
浏览 11

请教C语言getchar()问题


#include<stdio.h>
int main(void)
{
    int guess = 1;
    char response;
    printf("Pick an integer from 1 to 100. I will try to guess ");
    printf("it.\nRespond with a y if my guess is right and with");
    printf("\nan n if it is wrong.\n");
    printf("Uh...is your number %d?\n", guess);
    while ((response=getchar()) != 'y')
    {
        if (response == 'n')
            printf("Well, then, is it %d?\n", ++guess);
        else
            printf("Sorry, I understand only y or n.\n");
        while (getchar() != '\n')
            continue;
    }
    printf("I knew I could do it!\n");

    return 0;
}

请教,这两个代码的区别是什么?如果输入no sir,getchar()是什么读取字符的,按照上面的代码,是while ((response=getchar()) != 'y')判断response=n,还是response=no sir?

#include<stdio.h>
int main(void)
{
    int guess = 1;
    char response;
    printf("Pick an integer from 1 to 100. I will try to guess ");
    printf("it.\nRespond with a y if my guess is right and with");
    printf("\nan n if it is wrong.\n");
    printf("Uh...is your number %d?\n", guess);
    while (getchar() != 'y')
    {
        printf("Well, then, is it %d?\n", ++guess);
        while (getchar() != '\n')
            continue;
    }
    printf("I knew I could do it!\n");

    return 0;
}

  • 写回答

4条回答 默认 最新

  • _术士_ 2023-11-03 08:26
    关注

    c语言的getchar是个大坑,初学者掉到坑里还爬不上来,关于这个函数我写过一篇文章,可以关注我找一下

    评论

报告相同问题?

问题事件

  • 创建了问题 11月2日

悬赏问题

  • ¥15 CCF-CSP 2023 第三题 解压缩(50%)
  • ¥30 comfyui openpose报错
  • ¥20 Wpf Datarid单元格闪烁效果的实现
  • ¥15 图像分割、图像边缘提取
  • ¥15 sqlserver执行存储过程报错
  • ¥100 nuxt、uniapp、ruoyi-vue 相关发布问题
  • ¥15 浮窗和全屏应用同时存在,全屏应用输入法无法弹出
  • ¥100 matlab2009 32位一直初始化
  • ¥15 Expected type 'str | PathLike[str]…… bytes' instead
  • ¥15 三极管电路求解,已知电阻电压和三级关放大倍数