由文件的读写 想到的 检测 代码有效行数的问题

前面对文件的读书 是基于 fstream::read()函数 直接将文件的内容copy到堆中,再去检测每一个字节的情况,但是后来发现有fstream::get()函数能够对文件中的每个字符进行检索。方便许多。

两种写法:

test.txt :

123456
1

1

#include <iostream>     // std::cout
#include <fstream>      // std::ifstream
#include <vector>

using namespace std;
int cnt;
int main () 
{
  cnt=0;
  
  fstream f;

  int length;
  f.open("test.txt",fstream::in|fstream::out|fstream::app);
  if(f)
  {
	cout<<"success"<<endl;
	f.seekg(0,f.end);
	length=f.tellg();
	f.seekg(0,f.beg);
	cout<<"length="<<length<<endl;
  }
  else
	cout<<"error"<<endl;
	
  while(f.good())
  {
	if(f.get()=='\n')
		cnt++;
  }
  
  cout<<"total row="<<cnt+1<<endl;
 
  return 0;
}


2

#include <iostream>     // std::cin, std::cout
#include <fstream>      // std::ifstream
using namespace std;
int main ()
{
  int  cnt=0;
  
  while(1)
  {
	  cnt=0;
	  char *str = new char [256];
	  cout << "Enter the name of an existing text file: ";
	  cin.get (str,256);    // get c-string

	  fstream is(str);     // open file

	  while (is.good())          // loop while extraction from file is possible
	  {
		char c = is.get();       // get character from file
		if(c=='\n') cnt++;
		if (is.good())
		  cout << c;
	  }
	  cout<<endl<<" total row ="<<cnt+1<<endl;
	  is.close();                // close file
	  delete[] str;
  }
  
  return 0;
}

在第二种方法下 出现了一些问题 


就是 cin.get()无法第二次 输入字符

对cin.get()研究

#include<iostream>
using namespace std;

int main()
{
    
	char a[10];
	char b[10];

		cin.get(a,10);
		cout<<"a"<<": "<<a<<endl;
		cin.get(b,10);
		cout<<"b"<<": "<<a<<endl;
		
}


网上查找 后发现  cin 和 cin.get() 

在cin这个对象里,有一个储存字符的流,可以想象成缓冲区,但事实上是cin里封装的一个东西.当我们在程序上输入字符后,对象cin获得了我们输入的字符,例如获得abcd,然后再通过.get()把流里面的第一个字符去掉,赋给cstr,这时,cin里储存的流的数据为bcd,而cstr则获得了 a.当我们再次运行bstr=cin.get();时,同理把cin里流的数据的b拿出来给了bstr,此后,cin里面的流的数据为cd,而bstr则为b,所以最后输出时,便能输出ab了

#include<iostream>
using namespace std;

int main()
{
    
	char a[10];
	char b[10];

		cin.get(a,10);
		cout<<"a"<<": "<<a<<endl;
		cin.get();
		cin.get(b,10);
		cout<<"b"<<": "<<a<<endl;
		
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值