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(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;
}
#include <iostream>
#include <fstream>
#include <string>
usingnamespace 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;
}