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

标签 c++ ifstream getline

首先,很抱歉,我的英语说得不是很好。 我的问题是我希望我的流返回文件的开头。所以,我在我的流对象上应用了 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;
}

非常感谢你(也感谢你警告我我的英语错误;))

最佳答案

调用 clear() 只会重置错误标志。要将流“倒回”到开头,您还需要使用 seekg :

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

请注意,此操作也可能会失败,因此您可能需要检查错误。

关于C++ getline() 在 clear() 之后,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22744537/

相关文章:

C++ - 如何创建一个 vector ,其中每个元素都是来自输入字符串的单个数字?

c++ - 使用打开的文件流创建类

c++ - 如何读入文件的末尾(或刚好在末尾之前)的字符?

c++ - 如何在 C++ 中将字符串转换为 vector ?

AWK - 使用 getline 将变量传输到系统 ()?

C++ getline 使用逗号作为分隔符的多个变量类型

c++ - resource.h 中的宏有什么用?

C++:如何在类中获取带有动态变量的私有(private)属性?

c++ - 如何在函数中逐行返回一个字符串?

c++ - 使用 C++ 从文件读取到单个内存块