C++实现控制台简单的Todolist

C++实现控制台简单的Todolist

功能概述

  • 添加待办事项
  • 显示所有待办事项
  • 删除指定的待办事项
  • 退出程序
#include <iostream>
#include <vector>
#include <string>

class TodoList {
private:
    std::vector<std::string> tasks;

public:
    void addTask(const std::string& task) {
        tasks.push_back(task);
    }

    void displayTasks() const {
        if (tasks.empty()) {
            std::cout << "No tasks in the list." << std::endl;
            return;
        }

        std::cout << "Tasks:" << std::endl;
        for (size_t i = 0; i < tasks.size(); ++i) {
            std::cout << i + 1 << ". " << tasks[i] << std::endl;
        }
    }

    void deleteTask(int taskNumber) {
        if (taskNumber <= 0 || taskNumber > tasks.size()) {
            std::cout << "Invalid task number." << std::endl;
            return;
        }

        tasks.erase(tasks.begin() + taskNumber - 1);
        std::cout << "Task " << taskNumber << " deleted." << std::endl;
    }
};

void showMenu() {
    std::cout << "\nTodo List Application" << std::endl;
    std::cout << "1. Add Task" << std::endl;
    std::cout << "2. Display Tasks" << std::endl;
    std::cout << "3. Delete Task" << std::endl;
    std::cout << "4. Exit" << std::endl;
    std::cout << "Enter your choice: ";
}

int main() {
    TodoList list;
    int choice;
    std::string task;
    int taskNumber;

    do {
        showMenu();
        std::cin >> choice;

        switch (choice) {
            case 1:
                std::cout << "Enter a task: ";
                std::cin.ignore(); // Ignore newline left in the input stream
                std::getline(std::cin, task);
                list.addTask(task);
                break;
            case 2:
                list.displayTasks();
                break;
            case 3:
                std::cout << "Enter task number to delete: ";
                std::cin >> taskNumber;
                list.deleteTask(taskNumber);
                break;
            case 4:
                std::cout << "Exiting..." << std::endl;
                break;
            default:
                std::cout << "Invalid choice. Please try again." << std::endl;
        }
    } while (choice != 4);

    return 0;
}

复制代码到编辑器中即可运行。

用云无忧
© 版权声明
THE END
喜欢就支持一下吧
点赞13 分享
评论 共2条

请登录后发表评论