我如何重播我的主要功能?(读描述,难字标题)

How do I replay my main function? (Read description, hard to word title)

本文关键字:描述 标题 何重播 我的 功能      更新时间:2023-10-16

我提前为误导性的标题道歉,我真的不知道如何表达我的问题,没有更多的空间。我将从展示main函数开始。

int main() {
    int input;
    List List;
    cout << "Press '1' to add a node" << endl;
    cout << "Press '2' to view the list of nodes" << endl;
    cin >> input;
    if (input == 1) {
    List.addNode();
    }
    else if (input == 2) {
    List.PrintList();
    }    
}

因此,正如您可以看到的主函数的性质,用户将希望输入多个节点(input 1)。现在,如果我输入一个节点,程序就结束了。在一个完美的程序,我希望能够让用户输入尽可能多的数据点,因为他们想,也能够打印出来。这两个功能现在基本上是无用的,因为需要多个数据点,并且用户会想要重新打印他们输入的点。

用描述的方式:我的问题是我如何让main函数重播自己?

你真正想要的是一个一直发生在计算机科学领域的转变。您需要稍微修改一下您的代码,您的主函数实际上已经过时了。是时候重写你的代码了。

 int new_function() {
     int input;
     ... // Do the rest of your function here
 }
 int main() {
     int i;
     for (i=0; i < XXX; i++) {
         new_function();
     }
 }

根据你的程序是如何完全开发的,你可能想在main中循环,或者你可能想在new函数或其他地方循环。你的架构的那一部分你必须根据你的功能来决定。

祝你好运!

为什么不直接把它塞进while循环呢?

int main() {
   int input = 0;
   List nodeList;
   /*Loop till user chooses to exit.*/
   while(input != 3)
   {
      /*Display options for user and take output.*/
      cout << "Press '1' to add a node" << endl;
      cout << "Press '2' to view the list of nodes" << endl;
      cout << "Press '3' to exit" << endl;
      cin >> input;
      /*Add a node to list.*/
      if (input == 1) {
          nodeList.addNode();
      }
      /*Display node list.*/
      else if (input == 2) {
          nodeList.PrintList();
      } 
      /*Exit program.*/
      else if (input == 3) {
          return 0;
      }
      /*Re-prompt user to input again.*/
      else {
         cout << "Invalid input.. try again." << endl;
      }
   }
   /*Won't reach.*/
   return 0;
}

一个for循环将按照您的意愿重复多次。

int i=0;
for (i=0;i<10;i++){
   // do something 10 times
}

while循环也很好,正如另一个答案所指出的。

使用do-while循环,并添加一个cout<<"按3退出"。在do-while语句中包含所有的if-else语句,以便能够循环执行直到用户点击3。在while条件中,设置while(input!=3)