从文件中搜索字符串的功能

function of searching a string from a file

本文关键字:功能 字符串 搜索 文件      更新时间:2023-10-16

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

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版本在任何地方都可以找到子字符串,而不仅仅是在行开头(而是在价格处)。

不太清楚您想要做什么,但是如果普通char是无符号的,则while将永远不满足。(通常不是,所以你可能会侥幸逃脱。)而且,你没有提取在循环的行尾,所以你可能会看到它,而不是EOF,和在循环中传递太多次。我更倾向于这样写:

bool
in1( std::string const& target )
{
    std::ifstream in( "optab1.txt" );
    if ( ! in.is_open() )
        //  Some sort of error handling, maybe an exception.
    std::string line;
    while ( std::getline( in, line )
            && ( line.size() < target.size() 
                 || ! std::equal( target.begin(), target.end(), line.begin() ) ) )
        ;
    return in;
}

注意打开成功的检查。一个可能的原因是总是返回false表示您没有成功打开文件。(但我们不能知道,除非你检查状态后打开)