|
#include <iostream>
#include <string>
#include <list>
#include <vector>
#include <fstream>
using namespace std;
void separate_word (const string&str, vector <string>&svec)
{
string :: size_type pos = 0;
string :: size_type prev_pos = 0;
string word;
int lenOfWord;
while ((pos = str.find_first_of ('', pos))! = string :: npos)
{
lenOfWord = pos-prev_pos;
word = str.substr (prev_pos, lenOfWord);
svec.push_back (word);
prev_pos = ++ pos;
}
// the last word
lenOfWord = str.size ()-prev_pos;
word = str.substr (prev_pos, lenOfWord);
svec.push_back (word);
return;
}
void getstr (string file_read, vector <string>&svec_line)
{
ifstream infile (file_read.c_str ());
if (! infile)
{
cerr << "open file error" << endl;
exit (-1);
}
else
{
string textline;
while (getline (infile, textline, '\n'))
{
svec_line.push_back (textline);
}
}
}
void initList (list <string>&slist, vector <string>&svec)
{
vector <string> :: const_iterator cit = svec.begin ();
while (cit! = svec.end ())
{
slist.push_back (* cit);
}
}
int main ()
{
cout << "Please enter the file name:";
string file_name;
cin >> file_name;
vector <string> svec_line;
getstr (file_name, svec_line);
vector <string> :: const_iterator cit = svec_line.begin ();
vector <string> svec;
for (; cit! = svec_line.end (); ++ cit)
{
separate_word (* cit, svec);
}
Ranch
list <string> slist;
initList (slist, svec);
return 0;
} |
|