简体   繁体   中英

getline function reading random characters not in the file; two random characters are read along with the data in the notepad keyword.txt

#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;
}

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++;
}

也许这是unicode文件,并且您在文件的开头看到字节顺序标志字节

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"ma 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.

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 ); .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM