【问题标题】:How to make program working properly after using goto?使用goto后如何让程序正常运行?
【发布时间】:2021-01-01 16:08:23
【问题描述】:

在任何选择之后,我想询问用户是否要再次使用该程序,或者退出。但如果输入 y,代码将无法再次正常工作。我尝试了其他解决方案,例如清除内存等,但我不是很有经验,所以我不知道我在做什么。也对不起我的语言。这是我的代码的一部分。我有 13 种不同的选择,每个选择都一样


    char str[100];
    int selection;
    char selection2;
    int i;
    begin:

    printf("Welcome to the Character/String Specification program\n");
    printf("Please enter whatever you want \n");
    scanf(" %s", str);

      printf("\nSelect the specification you want\n");
      printf("1) is your input a letter?\n");
      printf("2) is your input a whitespace?\n");
      printf("3) is your input a decimal digit?\n");
      printf("4) is your input a hexadecimal digit?\n");
      printf("5) is your input an upper-case letter?\n");
      printf("6) is your input a lower-case letter?\n");
      printf("7) is your input a letter or a decimal digit?\n");
      printf("8) is your input a control character?(ACSII 0..31 and 127)\n");
      printf("9) is your input a not a letter, digit, whitespace, or invisible control character?\n");
      printf("10)is your input a printable (ASCIII ' '..'~')\n");
      printf("11)is your input have a graphical representation\n");
      printf("12)Do you want to see your input as all upper characters?\n");
      printf("13)Do you want to see your input as all lower characters?\n\n");
      scanf(" %d",&selection);
      printf("\n");

      while(true)
      {
      if(selection == 1)
      {
       while(str[i])
          {
            if(isalpha(str[i]))
            {
                printf("%c is an alphabet\n",str[i]);
            }
            else
            {
                printf("%c is not an alphabet\n",str[i]);
            }
            i++;
          }
          printf("Do you want to go back to the start point? (y) for yes,(n) for no\n");
          scanf(" %c",&selection2);
          if(selection2=='y')
          {
              goto begin;
          }
          else if(selection2=='n')
          {
              printf("Goodbye\n");
              break;
          }

【问题讨论】:

  • 虽然标签和goto 的使用是可以接受的,但很少使用它来代替循环。
  • 另请注意,您的代码具有未定义的行为,因为您使用不确定的值作为数组索引。这可能是您的问题的根本原因:您没有初始化(或 re-初始化)一些变量。使用常见的调试技术可以很容易地检测到这个问题,包括使用实际的调试器在监控变量及其值的同时逐语句逐句执行代码。请花时间学习如何调试您的程序,这将使您作为程序员的生活更加轻松。
  • 我是编程新手,我会认真考虑您的建议,谢谢

标签: c++ c if-statement while-loop goto


【解决方案1】:

我会做这样的事情,而不是使用 goto:

int value = 1;
do {
   //enter your code here
   if(selection2=='n')
      {
          printf("Goodbye\n");
          value = 0;
          break;
      }
} while(value)

这将导致代码至少运行一次并根据用户输入继续运行。 Goto 不是最佳做法,因为它使阅读变得更加困难。

【讨论】:

  • 我发现 goto 非常适合打破嵌套循环。
猜你喜欢
  • 2018-02-20
  • 1970-01-01
  • 1970-01-01
  • 2010-09-27
  • 2012-01-07
  • 1970-01-01
  • 2020-09-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多