hi how would i go about checking if a number entered by the user is present in a file? i will not know what the user enters and the file is set out like
1 4 5 6 3 8
3 4 9
the only method i can think of is to check if the number the user enters IS the file, not is contained in the file
i'm brand new to c++ so help would be great thanks!
You only check once for number. You should use while loop, that goes through the file while there's still something to check(until EOF), and you check/count occurances of number.
#include <iostream>
#include <fstream>
#include <conio.h>
usingnamespace std;
int main()
{
int x;
cout << "Enter any value: ";
cin >> x;
int counter=0;
ifstream in("C:/problem2.txt");
int filenum;
while(inFile)//while not at the end of file
{
in>>filenum;
if(filenum == x)
counter++;
}
cout<<"\nThe number "<<x<<" has been found "<<counter<<" times.";
return 0;
}
while (in>>filenum) // while a number has been read successfully
{
Incidentally, above mention has been made of checking for end of file (eof). Generally that is not the most useful approach. Except in very specific situations it should be avoided.
Also this while(inFile) does not check for end of file. It actually checks whether a previous file operation failed.