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