用于C++的某种"转到"功能
Some kind of 'goto' function for C++
#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。
相关文章:
- 代码的效率. 转到和函数调用
- C++:我的开关盒循环转到第一种情况
- 转到基于范围的 for 循环中的下一个迭代器
- 如何在跳过所有内部实现的同时跳转到 GDB 中 std::function 中的函数?
- 更改 git 分支名称后,在项目的 Visual Studio 代码中丢失智能感知(建议,转到定义C++
- 我正在尝试为字符打印一些相应的值,但条件总是转到其他位置
- 需要从存档中读取一行文本.txt直到找到"hhh",然后转到下一行
- 如果类在堆上,函数是转到堆还是堆栈?
- 跳转到通过输入坐标定义的控制台屏幕位置
- 跳转到函数从某些代码部分开始
- 可以在没有构建代码的情况下转到定义吗?
- 跳转到if(false)块有问题吗
- 当我使用c++生成器时,如何在输入完成后自动跳转到下一个"TEdit"
- Cython:如何在不需要 GIL 的情况下从 numpy 内存视图转到矢量[对[双,双]]?
- 调试 - 单步执行 (F11) 不会直接转到函数
- 如何转到 fstream 中文件的开头?
- 是否可以在不指定类型的情况下从 istringstream 转到向量?
- 如何将自己的智能指针传递到功能
- 用于C++的某种"转到"功能
- "如何使用 vi 跳转到C++项目中的功能