【发布时间】:2023-03-30 13:38:01
【问题描述】:
大家! 我是 C++ 新手,唉,我犯了愚蠢的错误。 这是 .txt 文件内容的 sn-p:
<tag attr1="value1" attr2="value2" ... >
我想要完成的是解析 .txt 文件,生成以下输出:
Tag: tag
name: attr1
value: value1
name: attr2
value: value2
到目前为止我所做的没有用(我的问题是分隔符):
#include<iostream>
#include <sstream>
#include <string>
#include <vector>
#include <fstream>
using namespace std;
struct tagline{
string tag;
string attributeN;
string attributeV;
};
int main(){
vector<tagline> information;
string line;
tagline t;
ifstream readFile("file.txt");
while(getline(readFile,line)){
stringstream in(line);
getline(in,t.tag);
getline(in,t.attributeN,'=');
getline(in,t.attributeV,'"');
information.push_back(t);
}
vector<tagline>::iterator it = information.begin();
for(; it != information.end(); it++){
cout << "Tag: " << (*it).tag << " \n"
<< "name: " << (*it).attributeN << " \n"
<< "value: " << (*it).attributeV << " \n";
}
return 0;
}
我得到的只是 sn-p 的简单显示,因为它在 .txt 文件中格式化:
<tag attr1="value1" attr2="value2" ... >
如果有人可以提供帮助,我会很高兴。谢谢!
【问题讨论】:
-
这是因为您在一条线上多次排队。您可能希望 getline 进入缓冲区,然后根据行索引将其分配给成员。更好的解决方案是重载
operator>>。 -
我不太明白的是如何使用多个分隔符执行缓冲区方法。你介意发布一个代码示例吗?如果不是太麻烦的话。 :)
-
是否可以选择使用 xml 解析器库?
-
看来我误解了问题陈述。在这种情况下,我会灌输一个新的
cctype。值是否包含空格?如果没有,这对cctype来说是小菜一碟。 -
@Stephan Lechner 我还没有真正使用过解析器库(不过我确实知道一些 XML),所以我不知道如何立即实现它。
标签: c++ string parsing variables output