使用C++ 写一个main函数,选择式完成不同函数的启用
时间: 2024-02-19 19:03:02 浏览: 24
以下是一个简单的例子,展示了如何使用选择结构启动对应的函数:
```c++
#include <iostream>
void function1() {
std::cout << "This is function1." << std::endl;
}
void function2() {
std::cout << "This is function2." << std::endl;
}
int main() {
int choice;
std::cout << "Enter 1 to execute function1 or 2 to execute function2: ";
std::cin >> choice;
switch (choice) {
case 1:
function1();
break;
case 2:
function2();
break;
default:
std::cout << "Invalid choice." << std::endl;
}
return 0;
}
```
在这个例子中,我们定义了两个函数`function1`和`function2`,分别打印不同的输出。在`main`函数中,我们首先读取用户的选择,然后使用`switch`语句判断用户的选择并分别执行对应的函数。如果用户输入了无效的选择,我们使用`default`分支打印一条错误消息。注意,C++中使用`cout`和`cin`代替了C语言中的`printf`和`scanf`。