Click here to Skip to main content
15,885,546 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to create a parser program in c++ so i can split each word / symbol into tokens. Am trying to split it by space, later will be split by '(',')','*','/', etc. I got a problem when input "Hello World", it just "d" which is saved. Any help, Thanks


C++
void main(){
	clrscr();
	char input[100], token[100], *temp[100];
	int lengthLine, i, pos, posTok;

	do{
		cout << ">>> "; cin.getline(input, 256);
		lengthLine = strlen(input);

		posTok = 0;

		for (pos=0;pos<lengthLine;pos++){
			if (input[pos] != ' '){
				strcpy(temp[posTok],&input[pos]);
			}else{
				posTok++;
			}
		}

		for (i=0;i<=posTok;i++){
			cout << temp[posTok] << endl;
		}
	}while(strcmp(input,"exit") != 0);
	getch();
}

[edit]Code block added - OriginalGriff[/edit]
Posted
Updated 13-Jun-15 22:05pm
v2

1 solution

The problem is that you aren't breaking it very well - look at your code.
You declare temp and an array of 100 "pointer-to-char" values, and you use strcpy to copy the whole remaining line into it:
C++
strcpy(temp[posTok],&input[pos]);
But...you never assign any values to the pointers, so they are all a bit random.
And you never terminate the "tokens" either.
What you need to do it set up temp, but then use malloc to allocate space for each token as you go.
What I would do is:
1) Create an array of token pointers.
2) Use malloc to allocate a "token string space", and set the first char to '\0'. Set it into the next free token array slot.
3) Loop thorugh each character in the input string
3.1) If it's a space copy a '\0' to the token, and allocate a new token space as in (2).
3.2) If it isn't, copy the character to the token.
4) Don't forget to use free to release the memory you allocated!

Make sense?
 
Share this answer
 
Comments
rudy-peto 14-Jun-15 7:25am    
Okay, My mistake in using 'strcpy', but I still don't get 'What would I do' things. Yes, It makes sense. Okay, lemme try to understand it slowly.. Thanks for helping
OriginalGriff 14-Jun-15 7:48am    
You're welcome!

Working out what to do is the hardest part - coding it is the easy bit :laugh:

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900