从文件中搜索字符串的功能 [英] function of searching a string from a file

查看:237
本文介绍了从文件中搜索字符串的功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我写的一些代码,用于检查文件中字符串的存在:

This is some code I wrote to check a string's presence in a file:

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。你能告诉我为什么会这样吗?

it is sure that the string being searched lies in the first column of the optab1.txt and in total there are two columns in the optab1.txt for every row. Now the problem is that no matter what string is being passed as the parameter s to the function always returns false. Can you tell me why this happens?

推荐答案

为什么不使用标准的C ++字符串和文件读取函数:

What a hack! Why not use standard C++ string and file reading functions:

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;
}

您可以替换 substr 通过更高级的字符串搜索功能,如果搜索字符串不需要在一行的开始。 substr 版本是最可读的,但它创建了子字符串的副本。 等于版本会就地比较两个字符串(但需要额外的大小检查)。 search 版本在任何位置找到子字符串,而不仅仅是在行的开头(但是以一个价格)。

You can replace substr by more advanced string searching functions if the search string isn't required to be at the beginning of a line. The substr version is the most readable, but it makes a copy of the substring. The equal version compares the two strings in-place (but requires the additional size check). The search version finds the substring anywhere, not just at the beginning of the line (but at a price).

这篇关于从文件中搜索字符串的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆