2

我正在制作一个简单的回文检测器,方法是将 int 转换为字符串,反转字符串并将字符串返回到 int 进行比较(也可以比较字符串,不是问题),但由于某种原因,反向字符串保留了前一个值并将新的值添加到行中,而不是替换它们……这是为什么呢?

#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;
}
4

2 回答 2

5

您每次都需要清除您的字符串流。你不断地向它附加东西并使字符串变大。

我会在循环中声明它,以便它每次都超出范围。我以前读过有关清除字符串流的问题。

于 2012-09-13T03:22:41.290 回答
3

This is because you are declaring your variable out outside of the nested for loops. this means the same out variable is used for every iteration and being appended to each time through the loop.

To fix simply this, you can move the stringsteam out line to inside of the inner for loop.

In general, you should be declaring your variables when you first use them to keep them in the smallest containing scope unless you have a particular reason not to. This also prevents accidental usage of uninitialized values. For instance, you can change the line temp = out.str() to string temp = out.str() and remove the string temp; line from the beginning.

于 2012-09-13T03:27:52.200 回答