在我的下面的代码中,我计算单词,行数,然后计算文本文件的大小.第一次使用seekg在第一次while循环之后工作正常但在第二次while循环之后,它不起作用.它给出了输出中显示的值.
#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
Run Code Online (Sandbox Code Playgroud)
最后一次输入操作会导致设置失败位.如果tellg在此位置位时调用它也将失败.你打电话clear()之前需要打电话tellg().
txtFile.clear(); // clear fail bits
txtFile.seekg(0,ios::beg);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1181 次 |
| 最近记录: |