【问题标题】:std::find : finding exact string c++ in a filestd::find :在文件中查找确切的字符串 c++
【发布时间】: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 126id:126还是126。我假设后者。3)只是为了指出如果您只是在寻找什么是 id,文件扫描可能不是最好的解决方案。 4)使搜索字符串为"\n246\n"
  • 文件每行包含 1 个 id,id 不是 int 它是一个字符串,它可以是 124arb ...当我执行 idInFile("246");尽管文件中没有“246”而是“2467”,但它返回true
  • 1) 你的设计是错误的。 2) line[found + argId.length()] &gt; '9' // match is good.

标签: c++ algorithm file search


【解决方案1】:

basic_string::find 根据its documentation 找到一个子字符串

在这种情况下,您需要完全匹配;请改用basic_string::compare==(后者在内部使用compare)。

【讨论】:

  • 我完全忘记了使用 == 运算符,它容易多了,我现在感到很惭愧:3
  • @Reda 如果你有一行带有"246abc" 的行,那它就不可能工作了。
  • if(line == argId) 返回真;返回假;问题出在哪里@ebyrob
  • @ebyrob:你这是什么意思?当然它会起作用(它会像预期的那样报告示例246 的“不等于”)。
  • whatever... @Reda 写道:“文件每行包含 1 个 id,id 不是 int 它是一个字符串,它可以是 124arb ...当我执行 idInFile("246" ); 尽管 "246" 不在文件中,但它返回 true,但 "2467" – Reda 16 分钟前" ---- ie: line is: "124arb" 但是是的,这与问题中的内容不同...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-16
  • 2017-10-10
  • 1970-01-01
  • 1970-01-01
  • 2022-12-09
  • 2013-04-18
相关资源
最近更新 更多