Menu
CoddyTech

查看任务

本课属于 Coddy C++ 学习旅程的“逻辑与流程”单元。第 20 课,共 56 课。

challenge icon

挑战

简单

扩展你的任务列表工具,实现查看功能,以编号列表的形式显示所有任务。这是在上一课的基础上新增查看系统中已存储任务的功能。

将提供以下输入:

  • 一个整数 n,表示要添加到列表中的任务数
  • 然后是 n 条任务描述,每行一条。每条描述都是一个单词,因此请使用 std::cin >> task 读取:如果在 std::cin >> n 后立即使用 getline,它会把数字所在行剩余的空内容读作第一个任务。

你的程序应当:

  1. 使用与上一课相同的设置开始(创建一个名为 tasks 的空 std::vector<std::string>,并显示欢迎消息)
  2. 读取任务数,并使用 push_back() 将每条任务描述添加到 vector 中
  3. 使用 .empty() 方法检查任务 vector 是否为空
  4. 如果 vector 为空,打印一条表示没有任务的消息
  5. 如果 vector 中有任务,使用带索引的传统 for 循环遍历它
  6. 以编号列表的形式打印每项任务,编号从 1 开始(不是 0)
  7. 最后显示任务总数

使用以下精确的输出格式:

任务列表为空时:

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++ 在线编译器