function of searching a string from a file
This is some code I wrote to check a string's
presence in a file:
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.putba开发者_如何学Gock(c);
in>>x;
in>>y;
if(x==s)
return true;
}
return false;
}
it is sure that the string being searched lies in the first column of the optab1.txt
and in total there are two columns in the optab1.txt
for every row.
Now the problem is that no matter what string is being passed as the parameter s
to the function always returns false. Can you tell me why this happens?
What a hack! Why not use standard C++ string and file reading functions:
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;
}
You can replace substr
by more advanced string searching functions if the search string isn't required to be at the beginning of a line. The substr
version is the most readable, but it makes a copy of the substring. The equal
version compares the two strings in-place (but requires the additional size check). The search
version finds the substring anywhere, not just at the beginning of the line (but at a price).
It's not too clear what you're trying to do, but the condition in the
while
will never be met if plain char
is unsigned. (It usually
isn't, so you might get away with it.) Also, you're not extracting the
end of line in the loop, so you'll probably see it instead of EOF
, and
pass once too often in the loop. I'd write this more along the lines
of:
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;
}
Note the check that the open succeeded. One possible reason you're always returning false is that you're not successfully opening the file. (But we can't know unless you check the status after the open.)
精彩评论