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

4 回答 4

1

您不检查是否getline()确实成功读取了该行。您的循环应检查的返回值getline()

while(getline(input,t)) {
    L.insert_ordered(t);
    L++;
}
于 2010-10-29T23:40:58.337 回答
0

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

于 2010-10-29T23:42:13.770 回答
0
void keywords::load()
{    
    string t;    
    while(input)    
    {        
        getline(input,t);//error line        
        L.insert_ordered(t);        
        L++;    
    }    
    L.print(cout);
}

这是一条关键线:

while(input) 

这实际上转化为:

while(!input.fail()) 

查看http://www.cppreference.com/wiki/io/eof上的 ifstream::fail() 文档。它解释了 ifstream::fail() (和 eof() )是如何工作的。在您的情况下, input.fail() 应在尝试从文件中读取之后立即检查,但在尝试使用读取值之前。

换句话说,您必须在 getline(..) 之后但在 L.insert_ordered(...) 之前立即检查

尝试这个 -

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

这是另一种方法:

void keywords::load()
{    
    string t;  

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

        getline(input,t);

    }    
    L.print(cout);
}

我没有尝试编译和运行这些,所以你可能想自己解决这个问题,但我希望你能得到大致的想法。我不确定你的程序的其余部分是否工作正常(我有点不确定你的代码中 L++ 的用途),但我希望解释如何使用 ifstream::fail() (或隐式调用它通过直接测试流)有帮助。

于 2010-10-31T00:00:34.937 回答
-1

奇怪的行为。这真的是编译吗?你能用一些输出来说明吗?我问的原因是,据我所知, getline实际上是这样定义的: istream& getline (char* s, streamsize n );.

于 2010-10-29T23:40:53.417 回答