1
在我的下面的代码中,我计算了单词,行数,然后计算文本文件的大小。第一次使用seekg
工作正常后,第一个while
循环但第二个while
循环后,它不工作。它给出的值如输出中所示。seekg第二次调用不起作用
#include <iostream>
#include <fstream>
using namespace std ;
int main(void)
{
fstream txtFile;
txtFile.open("test.txt");
if(txtFile.is_open())
{
printf("txt file is opened");
}
//number of words and lines in txt file
int w=0 , l =0 ;
int c , start , end;
string s;
while(1)
{
if(txtFile.peek() == -1)
break;
c = txtFile.get();
if(c != txtFile.eof())
w++;
}
txtFile.seekg(0,ios::beg);
while(getline(txtFile,s))
{
l++ ;
}
printf("no of words : %d , no of lines: %d\n",w,l);
//calculate the size of both the files
txtFile.seekg(0,ios::beg);
start = txtFile.tellg();
printf("%d\n",start);;
txtFile.seekg(0, ios::end);
end = txtFile.tellg();
printf("%d\n",end);;
return 0 ;
}
OUTPUT
txt file is opened
no of words : 128 , no of lines: 50
-1
-1
+1不同之处在于第一个循环只设置'eofbit',而第二个循环设置'eofbit'和'failbit'。 'seekg()'自动清除'eofbit',但如果设置了其他标志则失败。 – jrok
@CaptainObvlious先生,你能告诉你说的是哪个“最后输入操作”吗?另外,请告诉你如何知道失败位是否设置? – Subbu
@CodeJack对'getline(txtFile,s)'的调用和我知道,因为标准告诉我这样 –