0

我目前正在自学 C 和 C++。在这个小小的“程序练习”中,我要求用户输入“i”或“d”以了解他们是要使用整数还是小数(浮点数)。我有一个while循环,通过告诉他们是否输入了错误的字符来确保用户输入'i'或'd'。出于某种原因,while 循环中的提示在进入 getchar() 之前会打印两次。在这种情况下,我很难理解幕后发生的事情。任何帮助都非常感谢。我正在使用 Xcode(不知道它是否相关)。

#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()
   }
 }

所以我得到的输出是这样的:

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

3 回答 3

4

发生的情况是,当您输入一个字符并按回车键时,您实际上是在输入两个字符 - 字符和回车符('\n')。循环对每个字符执行一次。这就是为什么你看到它经历了两次。

诀窍是明确过滤掉返回字符,如下所示:

#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();
   }
}
于 2013-07-26T23:25:28.410 回答
1

正如Ziffusion在他的回答中正确诊断的那样,您会收到双重提示,因为您在用户输入错误后获得换行符作为单独的字符,而这也不是inor d

这是一个有一些改进的重写:

#include <stdio.h>

int main(void)
{
    char action = '\0';

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

    while (scanf(" %c", &action) == 1 && action != 'i' && action != 'd')
        printf("You didn't enter the right command. Please try again (i/d): ");

    printf("Action selected: %d\n", action);
}

有什么改变?

  1. 提示不会以换行符结束,因此用户的响应会立即出现在它之后。标准 I/O 通常同步标准输出和标准输入,以便刷新提示,尽管不以换行符结尾。如果没有出现提示,您可以在每个提示语句之后添加一个fflush(stdout);或。fflush(0);printf()

  2. 检查结果scanf()以处理 EOF。

  3. 的格式scanf()包括前导空格。这将在返回的字符之前跳过空格,因此您会得到一个非空白、非换行符。

  4. 原始条件action != 'i' || action != 'd'始终为真;你需要的&&

  5. Nitpick:改进错误消息的语法。

请注意,在循环之后,如果用户触发了 EOF(键入i或等效),则操作可能不是。如果您获得 EOF(例如,用户使用来自 的标准输入运行程序),则除了初始化为 之外,您将没有确定性值。dControl-D/dev/nullaction'\0'

于 2013-07-26T23:57:32.140 回答
0

在这里,我修复了您的代码:

#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') // here the loop will stop if action is 'i' or 'd'
       {
         printf("You didn't entered the right command. Please try again (i/d)\n");
         scanf("\n%c", &action);// here to deal with '\n'
       }
     }
于 2013-07-26T23:37:23.187 回答