Search code examples
c++cif-statementwhile-loopgoto

How to make program working properly after using goto?


After any selection, I want to ask the user if they want to use the program again, or quit. But if y is inputted code doesn't work properly again. I tried the other solutions like clearing memory etc but I am not very experienced so I don't know what I am doing. Also sorry about my language. This is a part of my code. I have 13 different selections each of them work the same


    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;
          }


Solution

  • instead of using goto, I would do something like this:

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

    This will cause the code to run at least once and continue running based on user input. Goto is not the best practice as it makes it harder to read.