如何在c++中打印目录

How to print table of contents in c++

本文关键字:打印 c++      更新时间:2023-10-16

我想打印一个目录,如下所示:

1 Data types and expressions
1.1 Data types in C++
1.2 Constants
1.2.1 What are Constants
1.2.2 Mathematical constant
1.2.3 Literal constant
1.3 Variables
1.3.1 What are variables
1.3.2 Variable naming rules
1.4 Operators in C++
1.5 Arithmetic operators
1.5.1 Basic rithmetic operators

使用类继承。应该有三个类:第一个标题(例如,1数据类型和~~(,第二个标题(~~中的1.1数据类型(,第三个标题(内容是什么(。我计划使用动态数组,因为我想打印的书可能会更改,或者我可能必须打印多本书。(标题的数量可能会改变(

这是我到目前为止的代码:

class First_Title {
public:
string first_name;
int first_num;
First_Title(string f_name, int f_num) : first_name(f_name), first_num(f_num){};
void print()
{
cout << this->first_name << "/" << this->first_num;
};
};
class Second_Title : public First_Title {
public:
string second_name;
int second_num;
Second_Title(string f_name, int f_num, string s_name, int s_num) : First_Title(f_name, f_num), second_name(s_name), second_num(s_num){};
};
class Third_Title : public Second_Title {
public:
string third_name;
int third_num;
};
int main()
{
return 0;
}

但我想这是一个错误的代码。

打印目录的最佳方式是什么?

这个结构将完成的工作

struct node  {
std::string title;
std::vector<node> child;
void print(int idx, string prefix) const {
cout << prefix << " " << title << std::endl;
prefix = "  " + prefix;
int inner_idx = 1;
for ( auto &c : child ) {
c.print(inner_idx++, prefix + to_string(inner_idx) + '.');
}
};
};

链接:https://godbolt.org/z/WazbfK