c - 为什么我收到错误 "Break statement not within loop or or switch."?

标签 c loops break

<分区>

这个简单的程序会询问用户的年龄,并根据年龄显示一条消息。最后,如果是这样,系统会询问用户是否愿意再次重复整个过程。但我收到了错误

Break statement not within loop or switch

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

#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 循环用错了?任何想法都会有所帮助。谢谢!

最佳答案

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

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 循环的执行。

关于c - 为什么我收到错误 "Break statement not within loop or or switch."?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16380511/

相关文章:

c - 算法查找 2 个字符串中常见字符的数量

php - 不能在同一个 Twig 文件中使用循环 2 次

loops - x86_64 - 汇编 - 循环条件和乱序

r - 中断/退出脚本

c# - Yield Break 是否返回一个值?

c++ - 将 C 代码转换为 .net(C# 或 VB.net)

c - 内存对齐与 CPU 利用率

C;如果我在 while 循环内的 for 循环中放置一个 break

c - 如何动态地进行array2d C

javascript - 为什么 Axios .then 和 .catch 函数会增加我的索引?