C/C++:如何使用制表从文本文件中读取序列化图形(树)

c/c++: How to read a serialized graph (tree) from text file with tabulation?

本文关键字:读取 文件 序列化 图形 文本 C++ 何使用      更新时间:2023-10-16


我正在尝试从文件中读取结构化数据(如图形或二叉树),它保存在带有indend的人类可编辑数据(无XML)中。

例如

       a
     /    
    b      c
   /     /  
  d   e  f    g

写成:

a
    b
        d
        e
    c
        f
        g

c++ 中是否有一些函数可以计算从行首开始连续出现的字符"\t"的次数?
我应该使用正则表达式吗?
我需要计算从行首到"\t"的第一个不同字符的"\t"(如果有的话)的数量。

提前谢谢你

用 getline 读取一行,然后遍历它,检查每个字符的 '\t':

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
    ifstream infile("test.dat");    
    string line;
    while (getline(infile, line))
    {   
        cout << line << endl;
        int tab_cnt = 0;    
        for (int ix = 0; ix < line.size(); ++ix)
            if (line[ix] == 't')
                ++tab_cnt;
        cout << tab_cnt << endl;
    }   
}