【问题标题】:extract names from a header file (string operation)从头文件中提取名称(字符串操作)
【发布时间】:2021-06-29 09:41:51
【问题描述】:

找不到错误:

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;

int main () {
    string line;
    ifstream myfile ("a.h");

    vector<vector<string>> vect;
  
    if (myfile.is_open())
    {
        while (getline(myfile, line) )
        {
            vector<string> temp;
            if (line.substr(0, line.find(" ")) == (string)"int"){
                temp.push_back(line.substr(line.find(" ")+1));
            }
            if (line[0] == '}' && line[line.size()-1] == ';')
            {
                string string_temp = line.substr(1, line.size()-1);

                cout << string_temp << endl;

                temp.insert(temp.begin(), string_temp);
                vect.push_back(temp);
                temp.clear();
            }
        }
        myfile.close();
    }
    else cout << "Unable to open file"; 
  
    for(auto t : vect){
        for(string s : t){
            cout << s << " ";
        }
        cout << endl;
    }

    return 0;
}

我需要从.h 文件中提取结构名称和成员名称; 其中a.h 看起来像这样:

typedef struct{
  int a;
  int b;
  int c;
}struct_req1_t;

 typedef struct{
  int d;
   int e;
   int f;
 }struct_rsp1_t;

 typedef struct{
    int g;
    int h;
    int i;
 }struct_req1_t;

我正在考虑将名称提取为二维向量:

structure_name1 member1 member2 member3
structure_name2 member1 member2 member3

【问题讨论】:

  • 还有什么问题?你得到编译器错误吗?请将其复制并粘贴到您的问题中。它不会产生所需的输出吗?请提供当前输出。
  • 如果您正在实现一个 .h 解析器,为什么不使用现有的:github.com/tree-sitter/tree-sitter 或 libclang?
  • 将 a.h 文件视为文本文件,我必须执行字符串和文件操作才能将名称转换为 2D 向量
  • 这段代码有很多错误。您的循环没有考虑到具有int 字段开始 的行带有空格,因此line.find(" ") 将在int 之前返回一个索引,因此line.substr(0, line.find(" ")) == (string)"int" 将始终是错误的。或者有些行是空白的,因此这些行的if (line[0] == '}' &amp;&amp; line[line.size()-1] == ';') 将是未定义的行为。或者line.substr(1, line.size()-1) 应该使用line.size()-2 而不是从提取的string 中省略尾随;

标签: c++ extract file-handling


【解决方案1】:

您可以使用cppast:它将为您提供抽象语法树,您应该能够从任何头文件中提取任何信息。 我成功地用它来创建一个远程代码生成器。

【讨论】:

    猜你喜欢
    • 2011-01-01
    • 1970-01-01
    • 2013-06-18
    • 2015-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-12
    相关资源
    最近更新 更多