前天突然有个想法,想把自己(源文件里的代码输出到控制台),于是就写了个初步的代码,如下:
#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;
}