简体   繁体   English

C ++中的字符串反转不是用新字符串替换旧字符串

[英]String reversal in C++ not replacing old string with new string

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? 我正在制作一个简单的回文检测器,通过将一个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;
}

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. 我已经阅读了过去清除字符串流的问题。

This is because you are declaring your variable out outside of the nested for loops. 这是因为你声明你的变量out嵌套以外的for循环。 this means the same out variable is used for every iteration and being appended to each time through the loop. 这意味着每次迭代都使用相同的out变量,并通过循环每次都附加。

To fix simply this, you can move the stringsteam out line to inside of the inner for loop. 要简单地修复此问题,您可以将stringsteam out行移动到inner for循环内部。

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; 例如,您可以将行temp = out.str()更改为string temp = out.str()并删除string temp; line from the beginning. 从一开始就行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM