Filehandling...coutning words

Hi All,

I have written below program to count number of words and lines and print the all the words.

#include <iostream>

using namespace std;
#include<fstream>
#include<string.h>
int main()
{
ofstream outfile;
outfile.open("venkat",ios::out);
if(!outfile)
{
cout<<"failed in opening file";
return 1;

}

string buff("I am wrting a c++ program in filehandling");


outfile<<buff;

outfile.close();


ifstream infile;
infile.open("venkat",ios::in);
if(!infile.is_open())
{
cout<<"unable to open file"<<endl;
return 1;
}
char*s=new char[350];
char*tempw;
int wordcount,linecount;

while(infile)
{ infile.getline(s,255);

while(tempw)
{
tempw=strtok(s," ");
cout<<tempw<<endl;
wordcount ++;
}

linecount++;
}
cout<<"word count is"<<wordcount<<"linecount is"<<linecount<<endl;
infile.close();
return 0;
}

Its compiling fine but when executed its dispplaying I infinite times...

No clue where I went wrong.

Guys Please help???


Thanks in advance.

Prasad
Please use code tags when posting code, to make it more readable.
Yeah use tags, and for your own sanity, not to mention ours, indent your code.

Many problems, main one is the wrong use of strtok. See below, also try "man strtok" or
http://www.cplusplus.com/reference/cstring/strtok/?kw=strtok
for more details.

1
2
3
4
5
6
7
8
9
10
while(infile.getline(s,255))
{ 
    tempw=strtok(s, " ");
    while(NULL != tempw)
   {
        cout<<tempw<<endl;
        wordcount ++;
        tempw = strtok(NULL, " ");
    }
}


Also you should #include <cstring> not string.h
That's curious positioning of your using directive
Gratuitous use of operator new
new not matched by delete []
several more, but I've lost the will to continue...
@tipaye
Thanks for your reply.
I wrote that in haste,didnt mind much about all these
Thanks for the comments....I will try to improve.
Topic archived. No new replies allowed.