用于C++的某种"转到"功能

Some kind of 'goto' function for C++

本文关键字:转到 功能 C++ 用于      更新时间:2023-10-16
#include <iostream>
using namespace std;
int main()
{
   float a, b, result;
   char operation, response;
   cin >> a >> operation >> b;
   switch(operation)
   {
   case '+':
         result = a + b;
         break;
   case '-':
         result = a - b;
         break;
   case '*':
         result = a * b;
         break;
   case '/':
         result = a / b;
         break;
   default:
         cout << "Invalid operation. Program terminated." << endl;
         return -1;
   }
   // Output result
   cout << "The result is " << result << endl;
   system("sleep 200");
   cout << "Do you want to make another opertaion? (Y/N)" << endl;
   cin >> response;
   if(response=='Y')
   {
    here
   }
   else if(response=='N')
   {
    cout << "The program will now close" << endl;
    system("sleep 500");
    return -1;
   }
   return 0;
}

在写"这里"这个词的地方,我想插入一个代码,让你到达代码的开头。

您可以使用循环do... while(condition)

喜欢:

do{
    cin >> a >> operation >> b;
    switch(operation)
    {
...
    }
    // Output result
    cout << "The result is " << result << endl;
    system("sleep 200");
    cout << "Do you want to make another opertaion? (Y/N)" << endl;
    cin >> response;
}while(response=='Y');

如果响应不是"Y",则循环结束,如果是循环,则重新开始

尽管goto在C++中非常不受欢迎,但它确实存在。就像汇编一样,你在代码中放了一个标签,然后告诉它使用 goto "跳"到那里。但是,与跳转在汇编中的工作方式相同,这可能会使您脱离所有循环,直到跳转到该点。

#include <iostream>
using namespace std;
int main()
{
   label: 
   float a, b, result;
   char operation, response;
   cin >> a >> operation >> b;
//condensed for neatness
   // Output result
   cout << "The result is " << result << endl;
   system("sleep 200");
   cout << "Do you want to make another opertaion? (Y/N)" << endl;
   cin >> response;
   if(response=='Y')
   {
    goto label;
   }
   else if(response=='N')
   {
    cout << "The program will no`enter code here`w close" << endl;
    system("sleep 500");
    return -1;
   }
   return 0;
}

大多数人会做的是使用do{}while(condition==true)循环或只是无限循环while(true)

对于这个"更整洁"的代码,你要做的是

#include <iostream>
using namespace std;
int main()
{
   do{
   float a, b, result;
   char operation, response;
   cin >> a >> operation >> b;
   //condensed for neatness 

// Output result

   cout << "The result is " << result << endl;
   system("sleep 200");
   cout << "Do you want to make another opertaion? (Y/N)" << endl;
   }while(cin.get() == 'Y');

    cout << "The program will no`enter code here`w close" << endl;
    system("sleep 500");
    return -1;
   return 0;
}

如果这是从另一个位置调用的,我强烈建议使用 do while 而不是 goto,因为它可能会导致问题。

goto 唯一真正的问题是它不优雅,并且使代码阅读起来令人困惑。您应该尽可能使用循环和返回,并且仅在您没有其他方法可以使其以最佳方式工作时才使用 goto。