I have this function that puts characters into a char* until it reaches a empty space or invalid character. The problem is that it works, well mostly... except I get really WEIRD extra "luggage" at the end of the string everytime I put it on display with cout. Its really irritating and I'm not sure what the problem is.
DefaultValidator is a function that basically returns true or false. My main purpose for this function is to return false if there is a space ' ' in the text file that I am parsing.
The end result of this function SHOULD be just '100', but it returns '100' plus extra junk.
C-style strings have to be null terminated (with a '\0' or 0 character.). That's how the computer knows it found the end of the string. Without it, it will keep printing whatever garbage follows the string data until it happens to stumble across a null.
You also are leaking memory:
1 2 3
return word; // once you return, the function stops here
delete[] word; // so word is never deleted
}
But all of this can be avoided if you use string to represent a string instead of an error-prone char array.
Your function, simplified and without memory leaks:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
string GetNextToken(char *buffer, int *index) {
string word;
int i = *index;
// Skip any spaces
while (DefaultValidator(buffer[i]) == false) {
i++;
}
while (DefaultValidator(buffer[i])) {
word.push_back(buffer[i]);
i++;
}
Sleep(2000);
return word;
}