在clear()之后的C++ getline()

问题描述 投票:1回答:1

首先,我很抱歉,但我的英语说得不是很好,我的问题是,我希望我的流回到文件的开头。所以,我应用 clear() 方法,但在这之后,我的流对象。getline() 归来 0 (false).我没有找到解决方案。有人知道这个问题吗?所以,这是我的代码。

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

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

c++ ifstream getline
1个回答
2
投票

调用 clear() 只重置错误标志。要将流 "倒带 "到开头,你还需要使用 seekg:

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

请注意,这项操作也可能失败,所以你可能要检查错误。

© www.soinside.com 2019 - 2024. All rights reserved.