Reputation: 1
I have a text file. All values stored in it are integers. When I compare the number I search for and the number stored in the text file, the result is incorrect!
My code:
ifstream infile ("h1.txt");
if (!infile)
{
cout << "Can't open file" << endl;
exit (EXIT_FAILURE);
}
int n;
infile >> n;
while(!infile.eof()){
if (n!=search)
{
return false;
}
else{
return true;
}
infile>>n;
}
Why does the compiler consider the result false even when n
is equal to search?
Upvotes: 0
Views: 558
Reputation: 1
I Solved the problem, number stores the last value only, i.e the value of number if the search found will be as the search hence, the condition will be true the bool value will be also true but when the file read the value not equal the search the compiler will entered in else section also and make the bool variable false although the search founded!(especially when the search number found in the beginning of the file), so I solved it by remove else and make the bool variable true if and only if the search is founded in the file. hope you understand
Upvotes: -1
Reputation: 16775
You are only reading the first number from the file whether is correct or not. The execution of a function ends when the code reaches a return
.
Upvotes: 2