Break ifstream input into words?

A

Adrian

dmurray14 said:
It is in fact work related to a class I'm taking, yes. So far, my plan
of attack is as follows: use getline to dump each line of the file into
a character array. Then, I'm going to run through the character array
looking for spaces, and pull out words every time I get to a space,
sending them into their own nodes. From there it should be easy to make
the framework to check to see whether the word has appeared before and
if so,just add to the count.

I don't think we're supposed to be making classes, no. The idea is
likely to stick to the basics so we get the concepts. Hopefully this
will work out...

Well you could try using the standard function strtok or implement you own
version of it. There is enough info in other posts for you to get the idea.

I have attached an example using strtok for splitting the words out of lines.

But remember c-strings are just arrays of chars with a null at the end. Think of
them a bit like an array of ints with the last being a 0. You can access each
element of the array the same way you would with integers and compare them the
same way. Just be careful you do not go past the end of the array - nasty things
can happen.

#include <cstdio>
#include <iostream>
#include <cstring>

using std::FILE;
using std::fopen;
using std::fgets;
using std::endl;
using std::cout;

//create a maximum for the len of a line
#define MAX_LINE 10000

//Our list of separators we wish to split at
const char *separator=" ,.?!";

int main()
{
FILE *fp;

//open the file
fp=fopen("file.txt", "r");

//check its open
if(fp)
{
//check for end of file
while(!feof(fp))
{
//char array to store our line
char line[MAX_LINE];

//ptr to each word NB if you want to move the word somewhere you
//will need to allocate memory for it
char *ptr;

//read a line from the file no longer the MAX_LINE-1 or till
//the next new line
fgets(line, MAX_LINE, fp);

//Remove newline from fgets or it could be in the separator list
line[strlen(line)-1]='\0';

//get a pointer to the first word
ptr=strtok(line, separator);

//check if therer is a word on the line
if(ptr)
{
cout << "Word [" << ptr << "]" << endl;
//see if there are more words. NB strtok remember the input line
//so a NULL is passed to say we want to use the same line as the
//last call
while(ptr=strtok(NULL, separator))
{
cout << "Word [" << ptr << "]" << endl;
}
}
}
}

fclose(fp);

return 0;
}


Adrian
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,817
Latest member
DicWeils

Latest Threads

Top