这是我编写的一些代码,用于检查文件中是否存在 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;
}
如果搜索字符串不需要位于行首,您可以用更高级的字符串搜索函数替换 substr
。 substr
版本是最易读的,但它会复制子字符串。 equal
版本就地比较两个字符串(但需要额外的大小检查)。 search
版本在任何地方找到子字符串,而不仅仅是在行的开头(但有代价)。
关于c++ - 从文件中搜索字符串的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7531890/