1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
|
#include <fstream>
#include<iostream>
using namespace std;
#include <cstring>
#include <iomanip>
#include <string>
string tokenizer (string line, bool first, size_t &i )
{
size_t j;
string token;
//Test to see if I am looking for the first word in a line,
//store the number of characters up to the first space into i
if (first == true)
{
i = line.find(' '); //store the number of characters up to the first space into i
if ( i == string:: npos)
{
cout<<"\no more tokens"<<endl;
//return an empty string if thre are no more tokens
token =""; //Going to look for an empty string to stop
return token; //my loop in main()
}
token = line.substr(0, i); //retrieve token
return token;
}
//**if NOT looking for the first token of a line *//
// always go (count) from i -----> j when tracking down number of characters
// from the place of the last retrived token (i+1),
// go find next spce, save that number of spaces in between, save that number into j
// basically *****|i----->j|****
j = line.substr(i+1, line.length()-i-1 ).find(' ');
if ( j == string:: npos)
{
cout<<"\no more tokens"<<endl;
token ="";
return token;
}
token = line.substr(i+1, j);//extract token
i = j;//Position of j is the starting place for the next token
return token;
}
int main( )
{
string line ;
bool first = true;
ifstream read;
read.open("test.txt");
if (read.fail() )
{
cout<<"error in input, exiting"<<endl;
return -1;
}
ofstream out;
out.open ("output.txt");
if (out.fail() )
{
cout<<"output file error, exititng..";
return -1;
}
size_t i, j;
string pi;
int k = 0;
while (!read.eof() )
{
getline(read, line );
cout << line << endl;
out << line <<endl; //Print lines to output file as i get them
i = 0; //since we are tokenizing a new line, restart position of i at 0,
first = true;
string token;
token = tokenizer (line, first, i);
cout << "\nfirst call of tokenenizer, it is: "<<token<<endl;
while ( token.length() !=0) //Looking for an empty string to stop the loop
{
first = false;
token = tokenizer ( line, first, i);
cout<<endl<<"ins "<<token<<endl;
}
}
return 0;
}
|