【发布时间】:2023-03-16 14:20:02
【问题描述】:
我想用std::find()查看文件中是否存在id,例如:
//file:
2467
435
24667
这里是函数:
bool idInFile(string argId)
{
std::ifstream anchorFile("anchors");
string line;
if(!anchorFile )//file not opened or empty
{
//cout << "file cannot be opened" << endl;
return false;
}
anchorFile.seekg(0, ios::end);
if(anchorFile.tellg() == 0)
{
//cout << "file is empty" << endl;
return false;
}
anchorFile.seekg(0, ios::beg);
while(getline(anchorFile, line))
{
std::size_t found = line.find(argId);
if (found!=std::string::npos)
return true;
}
return false;
}
在这种情况下:如果我尝试搜索 id 246,由于“2467”包含“246”,该函数返回 true,如果一行中仅存在 id“246”,我需要它返回 true。
【问题讨论】:
-
1) 可以使用正则表达式:
^246$。 2) 可以检查line.length() == 3。 3) 使用索引查找... -
我没有安装 boost,我在 debian 机器上编码,我非常喜欢使用 std::find(), ty 的解决方案来回答 btw :)
-
嗯...为什么需要提升正则表达式?啊。 2)如果没有额外的库很容易做到......(你的问题真的不清楚是
id 126,id:126还是126。我假设后者。3)只是为了指出如果您只是在寻找什么是 id,文件扫描可能不是最好的解决方案。 4)使搜索字符串为"\n246\n"。 -
文件每行包含 1 个 id,id 不是 int 它是一个字符串,它可以是 124arb ...当我执行 idInFile("246");尽管文件中没有“246”而是“2467”,但它返回true
-
1) 你的设计是错误的。 2)
line[found + argId.length()] > '9' // match is good.