用c++写一个跑腿小程序
时间: 2024-11-25 11:10:21 浏览: 3
在C++中编写一个简单的跑腿小程序,可以设计成命令行交互的程序,用于接收用户的请求并进行处理。这里我会提供一个基本的框架示例,假设我们有一个名为`TaskRunner`的类,它有添加任务(`addTask`)、查看任务列表(`viewTasks`)和完成任务(`completeTask`)等功能。
```cpp
#include <iostream>
#include <vector>
#include <string>
class Task {
public:
std::string description;
bool completed;
// 构造函数
Task(const std::string& desc) : description(desc), completed(false) {}
};
class TaskRunner {
private:
std::vector<Task> tasks;
public:
void addTask(const std::string& taskDesc) {
Task newTask(taskDesc);
tasks.push_back(newTask);
std::cout << "Task added: " << taskDesc << "\n";
}
void viewTasks() const {
if (tasks.empty()) {
std::cout << "No tasks available.\n";
} else {
for (const auto& task : tasks) {
std::cout << "ID: " << int(tasks.size() - 1) + 1 << ", Task: " << task.description << ", Completed: " << (task.completed ? "Yes" : "No") << "\n";
}
}
}
void completeTask(int taskId) {
if (taskId >= 0 && taskId < tasks.size()) {
tasks[taskId].completed = true;
std::cout << "Task completed: " << tasks[taskId].description << "\n";
} else {
std::cout << "Invalid task ID.\n";
}
}
};
int main() {
TaskRunner runner;
while (true) {
std::cout << "Select an option:\n"
<< "1. Add a task\n"
<< "2. View tasks\n"
<< "3. Complete a task\n"
<< "4. Exit\n"
<< "Enter your choice: ";
int choice;
std::cin >> choice;
switch (choice) {
case 1:
std::string taskDesc;
std::cout << "Enter task description: ";
std::getline(std::cin, taskDesc);
runner.addTask(taskDesc);
break;
case 2:
runner.viewTasks();
break;
case 3:
int taskId;
std::cout << "Enter task ID to complete: ";
std::cin >> taskId;
runner.completeTask(taskId);
break;
case 4:
std::cout << "Exiting...\n";
return 0;
default:
std::cout << "Invalid choice. Please try again.\n";
break;
}
}
}
```
这个例子是一个基础版本,实际应用可能会需要更复杂的错误处理、用户界面以及持久化数据存储。运行这个程序后,用户可以通过输入相应的数字选择操作,如添加新任务、查看任务列表等。
阅读全文