Weird problem with string function
Posted
by wrongusername
on Stack Overflow
See other posts from Stack Overflow
or by wrongusername
Published on 2010-03-12T06:07:44Z
Indexed on
2010/03/12
6:17 UTC
Read the original article
Hit count: 297
I'm having a weird problem with the following function, which returns a string with all the characters in it after a certain point:
string after(int after, string word) {
char temp[word.size() - after];
cout << word.size() - after << endl; //output here is as expected
for(int a = 0; a < (word.size() - after); a++) {
cout << word[a + after]; //and so is this
temp[a] = word[a + after];
cout << temp[a]; //and this
}
cout << endl << temp << endl; //but output here does not always match what I want
string returnString = temp;
return returnString;
}
The thing is, when the returned string is 7 chars or less, it works just as expected. When the returned string is 8 chars or more, then it starts spewing nonsense at the end of the expected output. For example, the lines
cout << after(1, "12345678") << endl;
cout << after(1, "123456789") << endl;
gives an output of:
7
22334455667788
2345678
2345678
8
2233445566778899
23456789?,?D~
23456789?,?D~
What can I do to fix this error, and are there any default C++ functions that can do this for me?
© Stack Overflow or respective owner