tags:

views:

33

answers:

4
#include "keywords.h"
#include <iostream>
#include <fstream>
#include "llist.h"
#include <string>
using namespace std;
//default constructor
List<string> L;
keywords::keywords(){

}
void keywords::open_file(string filename)
{
    input.open(filename.c_str());
}
void keywords::close_file(){
    input.close();
}
void keywords::load()
{
    string t;
    while(input)
    {
        getline(input,t);//error line
        L.insert_ordered(t);
        L++;
    }
    L.print(cout);
}
bool keywords::find(std::string token)
{
    L.start();
    if(L.find(token)==1)
        return 1;
    else return 0;
}
A: 

Strange behaviour. Is this actually compiling? Could you illustrate with some output? The reason i'm asking is because, to my knowledge, getline is actually defined this way: istream& getline (char* s, streamsize n );.

horacv
+1  A: 

You don't check if getline() did actually successfully read the line. Your loop should check the return value of getline():

while(getline(input,t)) {
    L.insert_ordered(t);
    L++;
}
sth
A: 

maybe this is unicode file and you are seeing the byte order flag bytes at the beginning of the file

pm100
A: 
void keywords::load()
{    
    string t;    
    while(input)    
    {        
        getline(input,t);//error line        
        L.insert_ordered(t);        
        L++;    
    }    
    L.print(cout);
}

Here is a key line:

while(input) 

This really translates to:

while(!input.fail()) 

Look at the documentation of ifstream::fail() at http://www.cppreference.com/wiki/io/eof. It explains how ifstream::fail() (and eof()) work. In your case, input.fail() should be checked immediately after attempting to read from the file, but before trying to use the read value.

In other words, you must check immediately after getline(..) but before L.insert_ordered(...)

Try this -

void keywords::load()
{    
    string t;    
    while(true)    
    {        
        getline(input,t);
        if (!input)
            break;         
        L.insert_ordered(t);        
        L++;    
    }    
    L.print(cout);
}

Here is another way you can do it:

void keywords::load()
{    
    string t;  

    getline(input,t);  
    while(input)    
    {               
        L.insert_ordered(t);        
        L++;    

        getline(input,t);

    }    
    L.print(cout);
}

I haven't tried to compile and run these, so you might want to work that out yourself, but I hope you get the general idea. I'm not sure if the rest of your program works ok or not (I"m a little unsure about the purpose of L++ in your code), but I hope the explanation about how to use ifstream::fail() (or implicitly calling it by testing the stream directly) helps.

Vatsan