2014-03-30 42 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