虽然循环重复的printf两次前往前的getchar()? [英] While loops duplicates printf two times before getting to getchar()?

查看:501
本文介绍了虽然循环重复的printf两次前往前的getchar()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,我正在学习对我自己的C和C ++。在这个小节目的做法我要求用户输入两个i或D知道自己是否想与整数或小数点(浮点)数字工作。我有一个while循环,使确保用户,告诉他们输入i或D,如果他们输入了错误的字符。出于某种原因,while循环中的提示才去的getchar打印两次()。我有一点很难理解什么在这种情况下,引擎盖下发生。任何帮助超级AP preciated。我使用的是X code(不知道这是否是相关的)。

 的#include<&stdio.h中GT;诠释的main()
{  字符动作;  的printf(请输入'我'与整数或'D'的工作与小数的工作\\ n \\ n);  scanf函数(%C,&安培;动作);   而(动作!='我'||行动!='D')
   {
     的printf(你没有输入正确的命令,请重试(I / D)\\ n);
     行动=的getchar()
   }
 }

那么,我得到作为输出是这样的:

 你没有输入正确的命令。请再试一次(I / D)
你没有输入正确的命令。请再试一次(I / D)


解决方案

正在发生的事情是,当你输入一个字符,打一回,你实际上是输入两个字符 - 字符和返回字符('\\ n' )。回路的每个字符执行一次。这就是为什么你看到它经历了两次。

关键是要明确地过滤掉回车符,就像这样:

 的#include<&stdio.h中GT;诠释的main()
{  字符动作;  的printf(请输入'我'与整数或'D'的工作与小数的工作\\ n \\ n);  scanf函数(%C,&安培;动作);   而(动作!='我'||行动!='D')
   {
     如果(行动!='\\ n')
     {
       的printf(你没有输入正确的命令,请重试(I / D)\\ n);
     }
     行动=的getchar();
   }
}

I'm currently learning C and C++ on my own. In this little "program practice" I ask the user to enter either 'i' or 'd' to know whether they want to work with integers or decimal (float) numbers. I have a while loop that makes sure the user enter 'i' or 'd' by telling them if they entered the wrong char. For some reason, the prompt inside the while loop prints two times before going to the getchar(). I'm having a bit of hard time understanding what's happening under the hood in this situation. Any help is super appreciated. I'm using Xcode (don't know if it's relevant).

#include <stdio.h>

int main()
{

  char action;

  printf("Please enter 'i' to work with integers or 'd' to work with decimals.\n\n"); 

  scanf("%c", &action); 

   while (action != 'i' || action != 'd')
   {
     printf("You didn't entered the right command. Please try again (i/d)\n");
     action = getchar()
   }
 }

So what I'm getting as an output is this:

You didn't entered the right command. Please try again (i/d)
You didn't entered the right command. Please try again (i/d)

解决方案

What is happening is that when you enter a character and hit a return, you are actually entering two characters - the character and the return character ('\n'). The loop executes once for each character. Which is why you see it go through twice.

The trick is to filter out the return character explicitly, like so:

#include <stdio.h>

int main()
{

  char action;

  printf("Please enter 'i' to work with integers or 'd' to work with decimals.\n\n"); 

  scanf("%c", &action); 

   while (action != 'i' || action != 'd')
   {
     if (action != '\n')
     {
       printf("You didn't entered the right command. Please try again (i/d)\n");
     }
     action = getchar();
   }
}

这篇关于虽然循环重复的printf两次前往前的getchar()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆