简体   繁体   English

我的案例陈述方法在c中两次打印一个句子

[英]My case-statement methode prints a sentence twice in c

I am trying to work with a switch-statement. 我正在尝试使用转换语句。 But it doenst really work for me, because if I run it, it prints the sentence ''task 1 = A, task 2 = B, task = C\\n'' twice after I choose A, B or C. Why is this/ What do I do wrong? 但是它确实对我有用,因为如果我运行它,在选择A,B或C之后,它将打印两次“任务1 = A,任务2 = B,任务= C \\ n”的句子。这是为什么/我做错了什么?

#include <stdio.h>
#include <stdlib.h>

main()
{
  int b;
     while (b)
     {
     char a;
  printf("task 1 = A, task 2 = B, task = C\n");
  scanf("%c", &a);


  switch ( a )
  {

     case 'A':
         printf("task 1\n");

     break;

     case 'B':
          printf("task 2\n");

     break;


     case 'C':
           printf("task 3\n");
     break;
}
}
}

On next iteration scanf read the \\n character left behind by previous scanf in input buffer. 在下一次迭代时, scanf读取输入缓冲区中前一个scanf留下的\\n字符。 A space before %c is able to consume any number of white-spaces. %c之前的空格可以占用任意数量的空格。
Try this 尝试这个

scanf(" %c", &a);
       ^ Place a space before `%c  

Another thing is that you have not initialized b . 另一件事是您尚未初始化b Your program invokes undefined behavior. 您的程序调用未定义的行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM