2014-03-30 40 views
1

首先,我很抱歉,但我的英语说得不好。 我的问题是,我想我的流回到文件的开始。所以,我将clear()方法应用于我的流对象,但在此之后,getline()始终返回0false)。 我找不到解决方案。有人有关于这个问题的想法? 所以,这是我的代码:C++ getline()在clear()后无效()

void Tools::tokenizeAll(string filename, string separator){ 
    char str[LINESIZE] = {0}; 
    int lineNumber = 0, j = 0; 

    ifstream stream; 
    stream.open(filename.c_str(), std::ifstream::in); 
    if(stream){ 
    while(stream.getline(str, LINESIZE)){ 
     lineNumber++; 
    } 

    //allocation dynamique du tableau à deux dimensions 
    string** elementsTable = NULL; 
    elementsTable = new string*[lineNumber]; 
    for(int i = 0 ; i < lineNumber ; i++) elementsTable[i] = new string[4]; 

    std::cout << " good()=" << stream.good() << endl; 
    std::cout << " eof()=" << stream.eof() << endl; 
    std::cout << " fail()=" << stream.fail() << endl; 
    std::cout << " bad()=" << stream.bad() << endl; 
    cout << endl; 

    stream.clear(); 

    std::cout << " good()=" << stream.good() << endl; 
    std::cout << " eof()=" << stream.eof() << endl; 
    std::cout << " fail()=" << stream.fail() << endl; 
    std::cout << " bad()=" << stream.bad() << endl; 
    cout << endl; 

    cout << stream.getline(str, LINESIZE) << endl;//return 0 


    } 
    else cout << "ERREUR: Impossible d'ouvrir le fichier en lecture." << endl; 
} 

非常感谢你(谢谢你提醒我,我的英语错误;))

+0

它不返回0,它返回被调用的'stream'。在通话过程中它可能达到了EOF。 – chris

+0

你为什么要打印getline的结果?也许你打算做'cin.getline(...);代替cout << str'。 – 0x499602D2

回答

2

调用clear()只复位错误标志。为了“倒带”流的开始,你还需要使用seekg

stream.seekg(0, std::ios::beg) 

注意,该操作可能会失败,太多,所以您可能要检查错误。

+0

它完美的作品。非常感谢你。 – Wmog