File search with loop

Hello. Can someone help me with my program? I can find the number I want to search in my file, but it will only work on the first loop. Otherwise, its gonna keep on saying it is not found even if the number is in the file. Any suggestions will be great :)

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

void intro(); //some explanations on how the program works

int main()
{
int count = 0, callers = 0;
string num, search;
bool flag = false;

ifstream file;
file.open ("PrizeList.txt");

if (!file)
{
cout<<"File is not available";
}
else
{
intro();
do
{
callers++;
cout<<"\nHello Caller. Guess a number between 1-500: ";
getline(cin, search);

if (search == "-1")
{
break;
}

while(!file.eof())
{
getline(file, num,'\n');
count++;

if(num == search)
{
cout<<"Caller. Your number "<<num<<" was found at location "<<count<<" of the list."
<<"\nCounting you, there were "<<callers<<" callers. Your winnings are $10,000.";
flag = true;
break;
}
}
if(!flag)
{
cout<<search<<" is not in the list. Call again.\n"<<endl;
}
}while(!flag);
}
file.close();
return 0;
}
Last edited on
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

//void intro(); //some explanations on how the program works

int main()
{
	int count = 0, callers = 0;
	string num, search;
	bool flag = false;

	ifstream file;
	file.open("PrizeList.txt");

	if (!file)
	{
		cout << "File is not available";
	}
	else
	{
		//intro();
		
		do
		{
			callers++;
			cout << "\nHello Caller. Guess a number between 1-500: ";
			getline(cin, search);

			if (search == "-1")
			{
				break;
			}

			while (!file.eof())
			{
				getline(file, num, '\n');
				count++;

				if (num == search)
				{
					cout << "Caller. Your number " << num << " was found at location " << count << " of the list."
						<< "\nCounting you, there were " << callers << " callers. Your winnings are $10,000.\n";
					flag = true;
					break;
				}
				else
				{
					cout << num << " is not in the list. Call again.\n" << endl;					
				}
			}
			
		} while (!flag);
	}
	
	
	file.close();
	system("pause");
	return 0;
}
Line 50 is in the wrong place because you can't tell for sure whether the number is in the file until you've checked the entire file. Delete lines 48-51 and insert this at line 53:
1
2
3
if (!flag) {
    cout << num << " is not in the list. Call again.\n" << endl;
}
Ahhhhhh... thanks guys!
Topic archived. No new replies allowed.