【发布时间】: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] == '}' && line[line.size()-1] == ';')将是未定义的行为。或者line.substr(1, line.size()-1)应该使用line.size()-2而不是从提取的string中省略尾随;。
标签: c++ extract file-handling