1

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

4

2 回答 2

5

什么黑客!为什么不使用标准 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;
}

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

于 2011-09-23T16:14:43.803 回答
1

目前还不清楚您要做什么,但是 如果 plain未签名,while则永远不会满足条件中的条件。char(它通常不是,所以你可能会侥幸逃脱。)另外,你没有在循环中提取行尾,所以你可能会看到它而不是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 的一个可能原因是您没有成功打开文件。(但除非您在打开后查看状态,否则我们无法知道。)

于 2011-09-23T16:47:50.190 回答