【问题标题】:getchar() not waiting for input and jumping directly to next linegetchar() 不等待输入并直接跳转到下一行
【发布时间】:2020-04-08 21:32:58
【问题描述】:

getchar() 不等待输入并直接跳转到下一行。我认为 scanf 和 getchar 之间存在一些不匹配,但无法弄清楚它到底是什么。

#include<stdio.h>
#include<ctype.h>

int main()
{

char ch;
int n1,n2;

printf("Enter the operation of your choice\n");
printf("a. add\ts. subtact\nm. multiply\td. divide\nq. quit\n");

while((ch=getchar())!='q')
{
 printf("\nEnter 1st number:\n");
    if(scanf("%d",&n1)!=1)
    {
        printf("Please enter an integer value.\n");
        continue;
    }
       printf("Enter 2nd number:\n");
    if(scanf("%d",&n2)!=1)
    {
        printf("Please enter an integer value.\n");
        continue;
    }  

 switch(ch)
    {
        case 'a':
        { printf(" %d + %d = %d\n",n1,n2,n1+n2);
          break;  
        }

        case 's':
        {
            printf(" %d - %d = %d\n",n1,n2,n1-n2);
            break;
        }

        case 'm':
        {
            printf(" %d * %d = %d\n",n1,n2,n1*n2);
            break;
        }

         case 'd':
        {

            if(n2!=0)
            {
            printf(" %d / %d = %f\n",n1,n2,(float)n1/n2);
            break;
            }
            else
            {
                printf("Enter a non-zero number for n2\n");
                continue;
            }

            break;
        }

    }

 printf("Enter the operation of your choice\n");
 printf("a. add\ts. subtact\nm. multiply\td. divide\nq. quit\n");
  }
  printf("Bye.");
 }

输出:

输入您选择的操作

一个。加 s。减法

米。倍增 d.划分

问。退出

一个

输入第一个数字:

50

输入第二个数字:

25

50 + 25 = 75

输入您选择的操作

一个。加 s。减法

米。倍增 d.划分

问。退出

输入第一个数字:

【问题讨论】:

  • getchar 也读取空格。例如,对应于输入键 Enter 的换行符 '\n'。改用 scanf("%c", &ch);
  • 这能回答你的问题吗? scanf getchar function is skipped

标签: c scanf getchar


【解决方案1】:

你的getchar在你给scanf读取的值时读取你输入的换行符和其他空格,你需要绕过这些空格

只是替换

while((ch=getchar())!='q')

通过

 while ((scanf(" %c", &ch) == 1) && (ch != 'q')) 

注意 '%' 前面的空格,这是因为它绕过了包括换行符在内的空格

【讨论】:

  • 谢谢你,我会这样做的
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-14
  • 2011-04-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多