前面对文件的读书 是基于 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;
}
#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;
}