C++ 从文本文件中提取文件名
我需要将文件名及其扩展名从输入文本文件提取到字符串向量。 输入文本文件非常混乱,用作某些应用程序的配置文件 关于我试图提取的文件名,我知道它们前面有一个“file=”提到,文件名在“”或“”之间引用。示例:file=“name.abc”。我也不能保证间距是多少:它可能是file=“name.abc”,file=“name.abc”,file=“name.abc”。。。延伸可以有不同的长度 因此,我尝试了以下代码:C++ 从文本文件中提取文件名,c++,file,istringstream,C++,File,Istringstream,我需要将文件名及其扩展名从输入文本文件提取到字符串向量。 输入文本文件非常混乱,用作某些应用程序的配置文件 关于我试图提取的文件名,我知道它们前面有一个“file=”提到,文件名在“”或“”之间引用。示例:file=“name.abc”。我也不能保证间距是多少:它可能是file=“name.abc”,file=“name.abc”,file=“name.abc”。。。延伸可以有不同的长度 因此,我尝试了以下代码: std::vector<std::string> attachment
std::vector<std::string> attachment_names;
std::istringstream words(text_content);
std::string word;
std::string pst_extension(".abc"); // My code should support any extension
while (words >> word)
{
auto extension_found = word.find(abc_extension);
if (extension_found != word.npos)
{
auto name_start = word.find("'") + 1;
//I am not even sure the file is quoted by ''
std::string attachment_name = word.substr(name_start, (extension_found + 3) - name_start + 1);
//Doing this annoys me a bit... Especially that the extension may be longer than 3 characters
attachment_names.push_back(attachment_name);
}
}
std::向量附件名称;
std::istringstream单词(文本内容);
字符串字;
std::字符串pst_扩展名(“.abc”);//我的代码应该支持任何扩展
while(words>>word)
{
自动扩展名\u found=word.find(abc\u扩展名);
if(找到扩展名)=word.npos
{
自动名称\u start=word.find(“”)+1;
//我甚至不确定该文件是否引用了“”
std::string attachment\u name=word.substr(name\u start,(扩展名\u found+3)-name\u start+1);
//这样做让我有点恼火…尤其是扩展名可能超过3个字符
附件名称。推回(附件名称);
}
}
有更好的方法吗?是否有可能更多地依赖文件标题来支持任何扩展?从C++11或使用boost,我建议您 使用正则表达式和正则表达式迭代器来解决这个问题,因为空间的数量不同,解析会变得有点混乱。 sregex_迭代器将遍历文本并匹配正则表达式(您可以将任何双向迭代器用作源,例如,使用
getline
获取的字符串)。一个未经检验的想法如下:
static std::regex const filename_re("[[:space:]]*file[[:space:]]*=(.*)[[:space:]]*");
std::regex_iterator rit(line.begin(), line.end(), filename_re), end;
while (rit != end) {
cout << rit[1] << ',';
++rit;
}
static std::regex const filename\u re(“[[:space:][]*文件[[:space:][]*=(.[:space:][]*”);
std::regex_迭代器rit(line.begin(),line.end(),filename_re),end;
while(rit!=结束){
等不及了,你在找代码审查吗?如果是的话,你可能想看看。我不知道这个社区,谢谢,伙计!:)你可能想看看那里的帮助中心,只是为了确保你的问题确实与主题有关,并对其进行适当修改:)谢谢我会的!谢谢你的建议!