查看任务
本课属于 Coddy C++ 学习旅程的“逻辑与流程”单元。第 20 课,共 56 课。
挑战
简单扩展你的任务列表工具,实现查看功能,以编号列表的形式显示所有任务。在上一课的基础上,添加查看系统中已存储任务的功能。
将提供以下输入:
- 一个整数
n,表示要添加到列表中的任务数量 - 接着是
n个字符串,表示任务描述
你的程序应当:
- 使用与上一课相同的设置开始(创建一个空的、名为
tasks的std::vector<std::string>,并显示欢迎消息) - 读取任务数量,并使用
push_back()将每个任务描述添加到 vector 中 - 使用
.empty()方法检查 tasks vector 是否为空 - 如果 vector 为空,打印一条表示没有任务的消息
- 如果 vector 中有任务,使用带索引的传统 for 循环遍历它
- 以编号列表的形式打印每个任务,编号从 1 开始(不是 0)
- 最后显示任务总数
使用以下精确的输出格式:
任务列表为空时:
Welcome to Task List Tool!
Menu Options:
1. Add Task
2. View Tasks
3. Quit
Task list system initialized and ready!
No tasks available.任务列表不为空时:
Welcome to Task List Tool!
Menu Options:
1. Add Task
2. View Tasks
3. Quit
Task list system initialized and ready!
Your Tasks:
1. [first task]
2. [second task]
3. [third task]
...
Total tasks: [number of tasks]使用传统的 for 循环,让 i 从 0 开始,直到 tasks.size()。打印时,显示 i + 1,使任务编号从 1 开始,并使用 tasks[i] 访问每个任务。
亲手试试
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main() {
vector<string> tasks;
cout << "Welcome to Task List Tool!" << endl;
cout << endl;
cout << "Menu Options:" << endl;
cout << "1. Add Task" << endl;
cout << "2. View Tasks" << endl;
cout << "3. Quit" << endl;
cout << endl;
cout << "Task list system initialized and ready!" << endl;
string taskDescription;
getline(cin, taskDescription);
tasks.push_back(taskDescription);
cout << "Task \"" << taskDescription << "\" added successfully!" << endl;
cout << "Total tasks: " << tasks.size() << endl;
return 0;
}逻辑与流程中的所有课
自己练习: C++ 在线编译器