从文件中搜索字符串的功能
function of searching a string from a file
这是我编写的一些代码,用于检查文件中是否存在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;
}
如果搜索字符串不需要在行首,可以用更高级的字符串搜索函数替换substr
。substr
版本是最易读的,但它会复制子字符串。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表示您没有成功打开文件。(但我们不能知道,除非你检查状态后打开)
相关文章:
- 我在 C++ 中创建了一个函数来递归反转字符串,但是之后如何使功能打印一个 endl?
- 自定义 {fmt} 格式化函数,具有编译时格式字符串检查功能
- 是否有用于执行反向字符串拆分器的开箱即用功能?
- 如何在C++中使用自定义比较功能对字符串进行排序?
- 如何比较C 中的两个字符串并使用默认功能
- 字符串manipluator在C 中使用所有功能
- 界面设计:超载功能的安全性采用字符串和字符阵列
- 如何使用字符串更改此插入功能以在链接列表中工作
- 从文件到字符串读取并传递到功能
- C 专用模板功能接收文字字符串
- 字符指针功能以复制C 中的字符串
- 返回字符串到主函数C 的功能
- C 库中是否有任何功能将字符串转换为算术操作
- 我希望在字符串功能上提供一些帮助
- 使用C RTTI(内置)通过字符串查找功能指针
- 该功能返回空字符串
- 将std ::字符串移至功能参数
- 功能已经具有字符串变量的主体和重新定义
- 用设置功能在类中设置字符串
- palindrome功能(字符串,堆栈,队列)