checking if a number present in a file

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!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <fstream>
#include <conio.h>

using namespace std;

int main()
{
	int x;
	
	cout << "Enter any value: ";
	cin >> x;
	int counter=0;

	ifstream in("C:/problem2.txt");
	int filenum;
	in >> filenum;
	if(filenum == x) 
		counter=counter+1;
		cout << counter;

		getch();
		return 0;
}
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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#include <fstream>
#include <conio.h>

using namespace 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;
}


Implement while loop to search through file.
Last edited on
Instead of
1
2
3
    while (inFile) 
    {
	 in>>filenum;

do this:
1
2
    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.
Topic archived. No new replies allowed.