I'm wrting some function which returns a string. But something werid happened. The output of the result string were printed as an unexpected thing from the console.
It becomes Chinese or something else or EMPTY STRING depending on the machine (TESTED). But this only happens when the input string is super long. It works normally for strings with a smaller size.
Is there a better way to append char to a string? It's because I suspect the problem was caused by the way how I added chars to the end of a string.
From Console
From Debugger
main.cpp
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
bool checkPalindrome(string s)
{
return (s == std::string(s.rbegin(), s.rend()));
}
string longestPalindrome(string s)
{
if (s.size() > 1000 || s.empty())
return "";
string result = "";
string sub = "";
char* ptr = &sub[0];
for (int i = 0; i < s.length(); ++i) {
sub += s[i];
while (true) {
string temp = ptr;
if (checkPalindrome(temp)) {
ptr = &sub[0];
if (temp.length() > output.length()) {
result = temp;
break;
}
break;
}
else {
ptr++;
}
if (ptr == &sub[sub.length()-1]) {
ptr = &sub[0];
break;
}
}
}
std::cout << "end of function" << std::endl;
return result;
}
int main()
{
string output = longestPalindrome("babaddtattarrattatddetartrateedredividerb");
std::cout << output << std::endl;
return 0;
}


Aucun commentaire:
Enregistrer un commentaire