0

I am trying to read a string from a file and compare it to another string. For some reason getline just returns and empty line.

int count =0;
string line;
ifstream emailFile;
emailFile.open("email.txt");


if (emailFile.is_open())
{
    cout << "file open \n";


while (emailFile.eof()!=true)
{
    getline(emailFile,line);
    cout <<line<<endl;


        for (int i=0; i<27; i++)
        {
            cout <<"line: "<< line << endl;
            cout<< "Spamword: "<< spamWords[i]<<endl;
            if (line.find(spamWords[i]) != string::npos)
            {
                cout <<"found line: "<< line << endl;
                cout<< "found Spamword: "<< spamWords[i]<<endl;
                count +=2;
            }

        }
}
}

else cout<< "file not found";

cout <<count;

}

I have tried troubleshooting it and I really don't see why nothing is being read.

Any help would be appreciated.

obsi
  • 53
  • 1
  • 8
  • 1
    Don't discard the return value of `getline`. – Kerrek SB Jul 24 '15 at 01:36
  • @KerrekSB yep. obsi, change out the `while (!eof)` line for `while (getline(emailFile, line))` That'll catch all the error conditions you're likely to care about. Give this a read too: http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong – user4581301 Jul 24 '15 at 01:39

1 Answers1

1

This person was having the same problem that you are having.

http://www.cplusplus.com/forum/beginner/27799/

Make sure that your txt file is in the same directory that the exe is built into. From the above link this line of code might help ensure you are actually in the file.

//Check if data file is open and reports
if(read.is_open())
  cout << "File ./" << file_name << " is open.\n";
  else
cout << "Error opening " << file_name << ".\n";
Questionable
  • 544
  • 2
  • 20