Jack K Jack K - 1 month ago 6
C++ Question

Getting a word after a certain character?

I'm trying to make myself a program that will take a String and give me the word after a certain character. So, for example:

String theString = "hello \t world"; // or "borld \t bello";


After the tab, I only want "world" and not "hello." This keeps crashing on me for some reason.

size_t delimiter = theString.find_last_of('\t');
char *test;

if (theString.find("hello") != string::npos) {
strcpy(test, theString.substr(delimiter + 1).c_str());
else if (theString.find("borld") != string::npos) {
strcpy(test, theString.substr(delimiter + 1).c_str());
}

cout << test;

Answer

From strcpy manual:

char *strcpy(char *dest, const char *src);

The strcpy() function copies the string pointed to by src, including the terminating null byte ('\0'), to the buffer pointed to by dest.

In your code, you declare test as a pointer to char* but you never initialize it.

test is therefore a pointer to indeterminate value. You then attempt to copy data to that inderminate location, resulting in the crash.

You can fix this easily by initializing test to point to memory you can strcpy to. Be sure to allow enough to not write beyond the buffer.