I am making a simple palindrome detector by converting an int to a string, reversing the string and making the string back to an int to compare it (could compare strings too, not the issue) but for some reason, the reverse string keeps the previous values and adds the new ones to the line rather than replacing them… why’s that?
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main(){
string tempreverse;
string temp;
stringstream out;
int tempnumber, tempnumber2;
int palindrome = 0;
for(int i = 100; i < 111; i++){
for(int j = 100; j < 111; j++){
tempnumber = i * j;
out << tempnumber;
temp = out.str();
tempreverse = string (temp.rbegin(), temp.rend());
tempnumber2 = atoi(tempreverse.c_str());
if (tempnumber == tempnumber2){
palindrome = tempnumber;
}
}
}
cout << palindrome << "\n";
cout << "Press ENTER to continue...";
cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
return 0;
}
You need to clear your stringstream each time. You keep appending stuff to it and making the string bigger.
I would declare it inside the loop so that it goes out of scope each time. I’ve read about issues clearing stringstreams in the past.