views:

75

answers:

2

Here is my main function:

int main(int argc, char **argv)
{
LoadFile();

Node *temp;
char *key;

switch (GetUserInput())
{
case 1:

    temp = malloc(sizeof(Node));

    printf("\nEnter the key of the new node: ");
    scanf("%s", temp->key);

    printf("\nEnter the value of the new node: ");
    scanf("%s", temp->value);

    AddNode(temp);
    free(temp);
    break;
case 2:
    key = malloc(sizeof(char *));
    printf("Enter the key of the node you want to delete: ");
    scanf("%s", key);
    DeleteNode(key);

    free(key);
    break;
case 3:
    PrintAll();
    break;
case 4:
    SaveFile();
    break;
case 5:
    return 0;
    break;
default:
    printf("\nWrong choice!\n");
    break;
}

return 0;
}

The only problem with it is that after any case statement breaks, the program just exits out. I understand why, but I don't know how to fix it. I want the program to repeat itself each time even after the case statements. Would I just say:

main(argc, argv);

before every break statement?

+2  A: 

wrap it in a while(1) { }

eg

while(1)
{
  //switch... etc down to the close of the switch
}
Keith Nicholas
A: 

After you reach a break statement control resumes at the end of the switch statement, so wrapping the entire switch in a while loop will make it repeat, but I would make it a separate function called from a loop in main:

void GetUserInput() {
  // switch
}

int main()
{
  while (1)
    GetUserInput();
  return 0;
 }
John Gordon
C doesn't have a keyword "true"
Keith Nicholas
@Keith Nicholas: C89/90 doesn't allow declaring variables in the middle of the code either. Since the OP does this, they must be using C99. C99 does have `true`, although it is not a keyword but rather a macro from `<stdbool.h>`.
AndreyT
@AndreyT: I didn't declare a variable in the switch statement. THAT'S C99. The variables were declared in the main function.
Mohit Deshpande
Apologies. I'm a C++ programmer by trade.
John Gordon
figured :-) also, you used the same function name that already exists in his code
Keith Nicholas