【问题标题】:Is it possible to use scanf() and getchar() in the same program to get input? [duplicate]是否可以在同一个程序中使用 scanf() 和 getchar() 来获取输入? [复制]
【发布时间】:2021-12-18 00:16:26
【问题描述】:

我正在努力完成我的作业,但偶然发现了一个与 scanf() 和 getchar() 相关的问题。这道题需要一个代码sn-p作为例子,要求学生证明这2个函数都可以从输入中检索到一个字符。

但是,当我尝试将它们放在同一个程序中时,只有第一个函数可以正常运行。后者被完全丢弃。

#include <stdio.h>

char letter;
int main()
{
    printf("I'm waiting for a character: ");
    letter = getchar();
    printf("\nNo, %c is not the character I want.\nTry again.\n\n",letter);

    printf("I'm waiting for a different character: ");
    scanf("%c",&letter);
    printf("Yes, %c is the one I'm thinking of!\n",letter);
    return(0);
}

output

我尝试过切换这两个函数的位置,但没有用。 有人可以帮我找到问题并提供解决方法吗?唯一的要求是程序需要输入两次,一次通过 getchar() 函数,一次通过 scanf()

【问题讨论】:

    标签: c input character


    【解决方案1】:

    第二次读取尝试只读取空格(行尾字符,因为您在第一个字母后按了 Enter)。只需将其替换为:

    scanf(" %c", &letter);
    

    % 之前的空格将告诉scanf 读取下一个非空白字符。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-07
      • 1970-01-01
      • 1970-01-01
      • 2015-05-23
      • 2011-07-29
      相关资源
      最近更新 更多