文件流的控制

      前天突然有个想法,想把自己(源文件里的代码输出到控制台),于是就写了个初步的代码,如下:

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main(void)
{
 ifstream in("2_3.cpp");   //该源文件的名字
 string word;                      //该源文件所含单词个数
 string line;                        //该源文件得行内容
 int count=0;                      //该源文件所含行有多少


 while( getline(in,line) )         //读取每行内容
 {
  cout << line << endl;
 }
 while( in>>word )                //读取单词
 {
  count++;
 }

 cout << count << endl;
 in.close();

 system("pause");
 return 0;
}///:~

可是运行结果却不是所期望的,只是成功显示了每行的内容,却没有显示所含单词个数。

当我DEBUG的时候,发现程序运行到 while( in>>word ) 的时候,in是个无效的流,于是我肯定,这是因为上次

读取完文件,到达文件结尾,返回了eof。

这时,我采取移动文件流,在成功打开文件后,作个标记ifstream::pos_type start_mark=in.tellg();当结束 

while( getline(in,line) )      

{
  cout << line << endl;
 }

后,就恢复流状态in.clear();然后回到所定位的地方in.seekg(start_mark);

这样,成功显示所含单词个数

整个成功的代码如下:

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main(void)
{
 ifstream in("2_3.cpp");
 string word;
 string line;
 int count=0;

 in.seekg(0,fstream::beg);
 ifstream::pos_type start_mark=in.tellg();
 
 while( getline(in,line) )
 {
  cout << line << endl;
 }
   
 //in.seekg(0,fstream::beg);
 in.clear();

 in.seekg(start_mark);
 while( in>>word )
 {
  count++;
 }

 cout << count << endl;
 in.close();

 system("pause");
 return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值