View Single Post
Old Feb 14th, 2007, 3:04 AM   #1
rwm
Professional Programmer
 
Join Date: Jan 2007
Location: Cape Town
Posts: 291
Rep Power: 2 rwm is on a distinguished road
problem with tokenizing

I guess I am pretty rusty at the moment No sorry, make that VERY rusty...

I'm having a problem with this program:

Given an input file that contains:

this is my loverly file

its very interesting innit!

hello?

I only get:

this is my loverly file

its very interesting innit!

The last word is being missed?

Heres the code:

#include <iostream>
#include <fstream>
using namespace std;

const char *inputFile = "c:\\testFile.txt";

int main() {

	ifstream in(inputFile,ios::in);
	if(!in) {

		cout << "error: could not get input file";

		return 1;

	}

	char ch;
	char token[100];
	unsigned int index=0;

	while(in.get(ch)) {

		//get tokens
		if(ch == ' ') {

			//got a token
			token[index] = '\0';

			cout << ' ' << token;

			token[0] = '\0';
			index = 0;

		} else {

			token[index] = ch;

			index++;

		}

	}

	cout << "\n\npress a key to exit...";
	while(!kbhit()) ;

	return 0;

}

I can't exactly remember how to store the token using a pointer, its very embarassing I know

I tried a test like this:

char *ptr = new char[100];

for(char ch='a'; ch<'f'; ch++) {

	*ptr = ch;

	ptr++;

}

*ptr = '\0';

but when I try to print it:

cout << ptr;

i get garbage... im doing something very wrong i know!

my cheeks are burning !

anyway, hope someone can help me out?

Thx

PS: reminder to myself to sit down and go over some "fundamentals" this weekend... hehe!
rwm is offline   Reply With Quote