Apr 4, 2015 at 7:01pm UTC
I am having trouble searching an file for a specific name. Every time I run the program it says the word is not found however I know it is in the file. Can you find any problems in my code?
#include <fstream>
#include <cstdlib>
#include <iostream>
using namespace std;
int main()
{
ifstream instream;
string name;
bool match=0;
instream.open("babynames2012.txt");
if (instream.fail( ))
{
cout << "Input file opening failed.\n";
exit(1);
}
cout << "Please enter a name: " << endl;
cin >> name;
while(!instream.eof())
{
string temp= "";
getline(instream, temp);
for(int i = 0; i < name.size(); i++)
{
if (temp[i]== name[i])
{
match= 1;
}
else
{
match= 0;
break;
}
}
if (match)
{
cout << name << " is ranked in popularity among names";
}
}
if (instream.eof() && (!match))
{
cout << "The name you entered is not found." << endl;
}
instream.close();
return 0;
}
Last edited on Apr 4, 2015 at 8:01pm UTC
Apr 5, 2015 at 1:51am UTC
This works although it may not be what you want, it does work.
I recommend researching why what you tried and why it did not work.
putting in a few cout statements should be all you need to do to see what I mean.
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
#include <fstream>
#include <cstdlib>
#include <iostream>
using namespace std;
int main()
{
ifstream instream;
string name;
bool match=0;
string temp= "" ;
instream.open("disk.txt" );
if (instream.fail( ))
{
cout << "Input file opening failed.\n" ;
exit(1);
}
cout << "Please enter a name: " << endl;
cin >> name;
while (!instream.eof())
{
getline(instream, temp);
if (temp== name)
{
match= 1;
break ;
}
}
instream.close();
if (match==1)
{
cout << name << " is ranked in popularity among names" ;
}
else
{
cout << "The name you entered is not found." << endl;
}
return 0;
}
Last edited on Apr 5, 2015 at 1:54am UTC