【问题标题】:getchar not working in switch case (c)getchar 在开关盒中不起作用(c)
【发布时间】:2012-11-19 12:01:23
【问题描述】:

使用一个非常简单的计算器程序,提示用户执行一项操作,然后提示输入两个整数以执行该操作。程序应该在这些操作之后循环,除非用户输入字符'q',此时程序应该退出。

#include <stdio.h>

int main (void)
    {
        char c;
        int number[2], num1, num2, result;
        double num1d, num2d, resultd;
        int done=1;

        while(done)
        {
        printf("\t What sort of operation would you like to perform? \n \t Type + - * / accordingly. \n");
        c = getchar();
        printf("\tplease enter a number \n");
        scanf("%d",&number[0]);
        printf("\tplease enter another number \n");
        scanf("%d",&number[1]);
        num1 = number[0];
        num2 = number[1];

        switch(c)
            {
            case('-'):
            result = num1-num2;
            printf("\nThe first number you entered subtracted by the second number is %d.\n", result);
            break;

            case('+'):
            result = num1+num2;
            printf("The first number you entered added to the second number is %d.\n", result);
            break;

            case('*'):
            result = num1*num2;
            printf("The first number you entered multiplied with the second number is %d.\n", result);
            break;

            case('/'):
            num1d = (double) num1;
            num2d = (double) num2;
            resultd = num1d/num2d;
            printf("The first number you entered divided by the second number is %g.\n", resultd);;
            break;

            case('q'):
            printf(" Now Exiting...\n");
            done=0;
            break;

            default:
            puts("Invalid key pressed. Press q to exit");
            break;
            }
        }

        return 0;
    }

单次计算正常工作,但随后执行异常;特别是它打印

printf("\t What sort of operation would you like to perform? \n \t Type + - * / accordingly. \n");
printf("\tplease enter a number \n");

一共。

清除输入缓冲区while (getchar() != '\n'); 的标准方法不能解决此问题。此文本显示不正确的两次用户仍然可以使用程序,就好像指令显示正常一样(因此用户可以键入操作,例如 +,回车,然后是一些整数和回车,并且程序将从那时起正确执行)每隔一次程序将“按下无效键。按 q 退出”,无论输入如何。

【问题讨论】:

    标签: c switch-statement getchar input-buffer


    【解决方案1】:

    这里的其他人说的是真的,getchar() 返回一个int,但这不是你的问题。

    问题是getchar() 在使用后会留下换行符。如果您要使用 getchar(),您必须在之后始终使用换行符。这个简单的修复:

       printf("\t What sort of operation would you like to perform? \n \t Type + - * / accordingly. \n");
        c = getchar();
        getchar();     //<-- here we do an extra getchar for the \n
        printf("\tplease enter a number \n");
        scanf("%d",&number[0]);
        printf("\tplease enter another number \n");
        scanf("%d",&number[1]);
    

    这将消除问题。每次你输入 &lt;somechar&gt;&lt;enter&gt; 时,它实际上是在缓冲区中放置两个字符,例如,如果我点击 + 并输入,我会得到:

    '+''\n'  // [+][\n]
    

    getchar() 只会得到其中的第一个,然后当再次调用getchar() 时,它不会等待您的输入,它只会接受'\n' 并继续使用scanf()

    【讨论】:

    • 谢谢兄弟,这很有用:)
    【解决方案2】:

    您不应将逐个字符与更高级的输入函数(例如scanf())混用。最好也使用scanf() 输入命令字符,但当然你必须在命令后按回车。我相信这是你问题的根本原因。

    顺便说一句,请注意getchar(),尽管它的名字,返回int不是char。这是因为它可以返回EOF,这是一个特殊常量,其值不同于所有字符的值。

    此外,您应该始终检查 I/O 函数的返回值,例如 scanf(),如果输入与模式字符串不匹配,它们可能会失败。

    作为调试提示,你当然可以在解释之前将c的值打印出来,这样你就更容易看到和理解程序的流程了。

    【讨论】:

    • 我听说 getchar() 返回整数的事实——这让我很吃惊。但是,您知道为什么这可能会导致奇怪的行为吗?
    • @Duncan - 它没有。您从getchar() 获取char 的事实仅意味着您的输入可能会溢出(即int 可以容纳的不仅仅是char)。你的问题是留下换行符(见我的回答)。
    【解决方案3】:

    我猜它第一次有效,但下次不行。这是因为scanf 调用将换行符留在输入缓冲区中,所以下次在循环中调用getchar 时,它将返回换行符。在scanf调用的格式后面加一个空格

    scanf("%d ",&number[0]);
    

    它会丢弃缓冲区中剩余的空白。

    使用调试器单步执行代码并检查变量以进行验证。

    【讨论】:

      【解决方案4】:

      您的 getchar 应该返回 int。原因如下

      getchar reads characters from the program's standard input 
      and returns an int value suitable for storing into a char. 
      The int value is for one reason only: not only does getchar 
      return all possible character values, but it also returns an 
      extra value to indicate that end-of-input has been seen. 
      The range of a char might not be enough to hold this extra value, 
      so the int has to be used.
      

      所以基本上你需要在代码中将char c 更改为int c

      【讨论】:

      • 虽然getchar() 确实返回int,但该建议并不能解决问题。
      猜你喜欢
      • 2015-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多