c++ - 从文件中搜索字符串的函数

标签 c++ function functional-testing file-search

这是我编写的一些代码,用于检查文件中是否存在 string:

bool aviasm::in1(string s)
{
ifstream in("optab1.txt",ios::in);//opening the optab
//cout<<"entered in1 func"<<endl;
char c;
string x,y;
while((c=in.get())!=EOF)
{
    in.putback(c);
    in>>x;
    in>>y;
    if(x==s)
    return true;
}
return false;
}

确定要搜索的字符串位于 optab1.txt 的第一列,并且 optab1.txt 中的每一行总共有两列. 现在的问题是,无论将什么字符串作为参数 s 传递给函数总是返回 false。你能告诉我为什么会这样吗?

最佳答案

多么骇人听闻!为什么不使用标准的 C++ 字符串和文件读取函数:

bool find_in_file(const std::string & needle)
{
  std::ifstream in("optab1.txt");
  std::string line;

  while (std::getline(in, line))  // remember this idiom!!
  {
    // if (line.substr(0, needle.length()) == needle)  // not so efficient
    if (line.length() >= needle.length() && std::equal(needle.begin(), needle.end(), line.begin())) // better
    // if (std::search(line.begin(), line.end(), needle.begin(), needle.end()) != line.end())  // for arbitrary position
    {
      return true;
    }
  }
  return false;
}

如果搜索字符串不需要位于行首,您可以用更高级的字符串搜索函数替换 substrsubstr 版本是最易读的,但它会复制子字符串。 equal 版本就地比较两个字符串(但需要额外的大小检查)。 search 版本在任何地方找到子字符串,而不仅仅是在行的开头(但有代价)。

关于c++ - 从文件中搜索字符串的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7531890/

相关文章:

c++ - 如何从 box2D 中的 Body* 获取 fixture 的 Shape 点?

c - 取相邻小区的最小值

javascript - Rails 功能测试assert_select javascript respond_to

JavaScript setInterval 函数可能有参数,也可能没有参数

.net - 仅对 future 项目业务规则进行自动化测试

ruby-on-rails - 如何在 rails 3 功能测试中发布 JSON 数据

c++ - 使用 std map 进行比较的运行时错误

c++ - 单例 : C++ shared dll

c++ - 即使已设置包含路径,Eclipse 也找不到头文件管理器

javascript - 转换为原始类型