Avi*_*mar 1 c++ function functional-testing file-search
这是我写的一些代码,用于检查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;
}
Run Code Online (Sandbox Code Playgroud)
确保被搜索的字符串位于第一列中,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;
}
Run Code Online (Sandbox Code Playgroud)
substr如果搜索字符串不需要位于行的开头,则可以使用更高级的字符串搜索功能替换.该substr版本的可读性最强,但它会生成子字符串的副本.该equal版本就地比较了两个字符串(但需要额外的大小检查).该search版本发现子的任何地方,不只是在生产线(但在价格)的开始.
| 归档时间: |
|
| 查看次数: |
3321 次 |
| 最近记录: |