The given code,
char file_data[10];
std::ifstream file_read ("D:\\myfile.txt");
cout<<"Enter the number to search"<<endl;
char val[10];
cin>>val;
while(!file_read.eof())
{
file_read>>file_data;
cout<<file_data<<endl;
}
if (val == file_data)
{
cout<<"Matched"<<endl;
}
else
{
cout<<"Not Matched"<<endl;
}
}
looks like this after running it through AStyle:
char file_data[10];
std::ifstream file_read ("D:\\myfile.txt");
cout<<"Enter the number to search"<<endl;
char val[10];
cin>>val;
while(!file_read.eof())
{
file_read>>file_data;
cout<<file_data<<endl;
}
if (val == file_data)
{
cout<<"Matched"<<endl;
}
else
{
cout<<"Not Matched"<<endl;
}
}
So, since the checking is done after the loop, checking only the last item read by the loop, even if you got the string comparison itself correct your program would not work.
The comparison doesn't work because, as others (rushing in) have already noted, you're comparing pointers, not strings.
To compare strings, use std::string
instead of character arrays.
Minor correction: instead of
while(!file_read.eof())
write
while(!file_read.fail())
or just
while(file_read)
which calls fail
for you (negating the result).
But doing this you would also have to check for success/failure of the input operation.
And the common idiom is to do that directly:
while( file_read>>file_data )