【问题标题】:c/c++: How to read a serialized graph (tree) from text file with tabulation?c / c ++:如何从带有制表的文本文件中读取序列化图(树)?
【发布时间】:2013-09-15 14:44:39
【问题描述】:


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

例如

       a
     /    \
    b      c
   / \    /  \
  d   e  f    g

写成:

a
    b
        d
        e
    c
        f
        g

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

提前谢谢你

【问题讨论】:

    标签: c++ regex serialization graph tree


    【解决方案1】:

    用 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;
        }   
    }
    

    【讨论】:

    • for 将在整行中计算 '\t',我只需要在开始时。 :) 很有帮助。
    猜你喜欢
    • 1970-01-01
    • 2011-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    • 2020-02-24
    相关资源
    最近更新 更多