回复 10楼 fl8962
因为你获取数目后,文件已经读完了程序代码:
#include <iostream> #include <fstream> #include <string> #include <vector> using namespace std; int main() { const char* filename = "dictionary"; ifstream infile( filename ); if( !infile ) { cerr << "Can't open this dictionary.\n"; return 1; } // 输入 size_t num = 0; vector<string> words; for( string word; infile>>word; ) { ++num; // 其实根本不需要,因为数量可以从 words.size() 获得 words.push_back( word ); } // 输出 for( size_t i=0; i!=words.size(); ++i ) cout << words[i] << '\n'; cout << "There are " << num << " words in this dictionary." << endl; return 0; }或者
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <iterator>
#include <algorithm>
using namespace std;
int main()
{
const char* filename = "dictionary";
ifstream infile( filename );
if( !infile )
{
cerr << "Can't open this dictionary.\n";
return 1;
}
// 输入
vector<string> words = vector<string>( istream_iterator<string>(infile), istream_iterator<string>() );
// 输出
copy( words.begin(), words.end(), ostream_iterator<string>(cout,"\n") );
cout << "There are " << words.size() << " words in this dictionary." << endl;
return 0;
}