为什么我收到错误“Break语句不在循环或切换中”?

时间:2013-05-05 01:20:39

标签: c loops break

这个简单的程序询问使用的年龄,并根据它显示一条消息。最后,如果是,则询问用户是否要再次重复整个事情。但是我收到错误

  

Break语句不在循环或开关

之内

当我编译它时。这是什么意思,我该如何纠正呢?

#include <stdio.h>
#include <string.h>

static int prompt_continue (const char *prompt)
   {
       printf("%s", prompt);
       char answer[5];
       if (scanf("%1s", answer) != 1)
     return 0;

       if (answer[0] == 'y' || answer[0] == 'Y')

{
    int c;
    while ((c = getchar()) != EOF && c != '\n')
    ;
    return 1;
}
return 0;
   }

   int main(void)
{
/*Creates a simple program using if else example. */



int age;

   while (printf("Welcome, this program is designed for if else statements.\n"));
   printf("Please enter your age.\n");

   scanf (" %d", &age); /*Enters age.*/
   if (age < 18){
   printf("You are young!\n");
}

else if (age > 18){
    printf("Ah you're old!\n");
  }

  {
    printf(" Woot.\n");
    if (prompt_continue("Do you want to try again? Y/N") == 0)
    break;
  }



   return 0;
}

试图解决这个问题,需要一些帮助。我使用了while循环错了吗?任何想法都会有所帮助。谢谢!

3 个答案:

答案 0 :(得分:2)

问题是你的break语句什么都不做,因为它不在循环或开关中,为什么你把它放在那里。

答案 1 :(得分:2)

您需要定义循环的范围。在这段代码中:

while (printf("Welcome, this program is designed for if else statements.\n"));
printf("Please enter your age.\n");
...
if (prompt_continue("Do you want to try again? Y/N") == 0)
    break;

你真正需要的是:

while (true)
{
    printf("Welcome, this program is designed for if else statements.\n"));
    printf("Please enter your age.\n");
    ...
    if (prompt_continue("Do you want to try again? Y/N") != 1)
        break;
}

break此处停止执行while循环。

答案 2 :(得分:1)

这就是您的错误所说的!! break语句必须位于loopifswitch-case的正文中,并将控件从该块中取出如果你想在那时结束程序,那么你应该在这里使用而不是中断:

 exit(0); //0 means successful termination, non-zero value means otherwise.

如果你想让整个事情再次重复,恐怕你的程序需要彻底检查。逻辑是错误的。让我检查......

编辑嗯,这是您的完整工作计划。我相信您会理解所做的更改。请在评论中告诉您的混淆(如果有的话)。这里是对更改的简要说明:< / p>

return函数中的prompt_contineu()个语句需要稍作修改,根本不需要getchar()while循环中没有任何条件main()函数及其正文在{}中没有明确定义,最后但并非最不重要的是,需要在prompt_continue()循环中调用while函数才能获得作业我希望你能看到continue声明的作用。顺便说一下,这个邪恶的程序说我 FRIGGIN OLD : - )

#include <stdio.h>
#include <string.h>

static int prompt_continue (const char *prompt)
   {
       printf("%s", prompt);
       char answer[5];
       if (scanf("%1s", answer) != 1)
     return 0;

       if (answer[0] == 'y' || answer[0] == 'Y')

{
    return 2;
    if (answer[0] == 'n' || answer[0] == 'N')
    return 3;
}
return 0;
   }

int main(void)
{
/*Creates a simple program using if else example. */



int age;

   while (1)
   {
   printf("Welcome, this program is designed for if else statements.\n");
   printf("Please enter your age.\n");

   scanf (" %d", &age); /*Enters age.*/
   if (age < 18)
   printf("You are young!\n");

   else if (age > 18)
    printf("Ah you're old!\n");

    printf(" Woot.\n");
    if(prompt_continue("Do you want to try again? Y/N")==3)
    break;
    else
    continue;
    }

   return 0;
}
相关问题