简体   繁体   English

通过C中的主要功能进行迭代?

[英]Iterate through main function in C?

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. 唯一的问题是,在任何case语句中断之后,程序都会退出。 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. 我希望程序即使在case语句之后也要重复一次。 Would I just say: 我可以说:

main(argc, argv);

before every break statement? 在每个中断语句之前?

wrap it in a while(1) { } 将其包装一会儿(1){}

eg 例如

while(1)
{
  //switch... etc down to the close of the switch
}

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: 到达break语句后,控制权将在switch语句的末尾恢复,因此将整个开关包装在while循环中将使其重复,但我将其设为从main中的循环调用的单独函数:

void GetUserInput() {
  // switch
}

int main()
{
  while (1)
    GetUserInput();
  return 0;
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM