1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 |
#include <iostream> #include <vector> #include <string> using namespace std; // Function to display the menu void displayMenu() { cout << "To-Do List Menu:" << endl; cout << "1. Add a task" << endl; cout << "2. Remove a task" << endl; cout << "3. List all tasks" << endl; cout << "4. Exit" << endl; cout << "Choose an option: "; } // Function to add a task void addTask(vector<string>& tasks) { string task; cout << "Enter the task description: "; cin.ignore(); // Ignore leftover newline character getline(cin, task); tasks.push_back(task); cout << "Task added." << endl; } // Function to remove a task void removeTask(vector<string>& tasks) { int index; cout << "Enter the task number to remove: "; cin >> index; if (index < 1 || index > tasks.size()) { cout << "Invalid task number." << endl; } else { tasks.erase(tasks.begin() + index - 1); cout << "Task removed." << endl; } } // Function to list all tasks void listTasks(const vector<string>& tasks) { if (tasks.empty()) { cout << "No tasks available." << endl; } else { cout << "To-Do List:" << endl; for (size_t i = 0; i < tasks.size(); ++i) { cout << i + 1 << ". " << tasks[i] << endl; } } } int main() { vector<string> tasks; int choice; while (true) { displayMenu(); cin >> choice; switch (choice) { case 1: addTask(tasks); break; case 2: removeTask(tasks); break; case 3: listTasks(tasks); break; case 4: cout << "Exiting To-Do List application." << endl; return 0; default: cout << "Invalid choice. Please try again." << endl; } } return 0; } |
Explanation
- Menu Display:
displayMenu()
: This function displays the main menu options: adding a task, removing a task, listing all tasks, and exiting the application.
- Adding a Task:
addTask()
: This function prompts the user to enter a task description and adds it to thetasks
vector. Thecin.ignore()
is used to clear the newline character left in the input buffer from previous operations.
- Removing a Task:
removeTask()
: This function asks the user for the task number to remove. It checks if the provided number is valid and, if so, removes the task from thetasks
vector. The task numbers are 1-based, so the index is adjusted accordingly.
- Listing All Tasks:
listTasks()
: This function displays all current tasks in thetasks
vector. If there are no tasks, it informs the user.
- Main Function:
- The
main()
function controls the application flow, continuously displaying the menu and handling user choices until the user chooses to exit.
- The