Hello,

I'm having a great deal of trouble stemming from a part in my code where I have to convert an integer into a string so that I can concatenate it - the problem being that a variable is refusing to clear or re-write itself, instead it just appends the new data when it ought to replace the old with the new completely. Here's some sample code, and where it's breaking:

#include <iostream>
#include <string>
#include <sstream>

using namespace std;

stringstream toString;

string converter;

void clear_converter(string&);
string int_to_s(int, string&);
string cypher(string);

int main()
{
  int number = 123;
  string converter;

  cout << int_to_s(number, converter) << endl;;
  clear_converter(converter);
  cout << int_to_s(456, converter) << endl;

    return 0;
}

//Defined Functions
/*This bit of code comes from various sources on the web
 *that say this is easiest way to convert int to str */
string int_to_s(int num, string& converter){
    toString << num;
    converter = toString.str();
    return converter;
}
/*A function that's supposed to clear "converter', but can't or doesn't
 *I've tried a plethora of ways in and out of functions and
 *in int main() itself to clear converter, but for the life of me I can't
 *and I don't know why */
void clear_converter(string& converter){
    converter.clear();
    }

From this, you would expect the output to be

123        //Expected Output
456

But instead, the output is:

123       //Actual Output
123456

As I said above, converter just appends the new data when I want it replaced no matter what I do. It's important that it's replaced because I'm running the code in a for loop in my main program, so converter is used to convert int to string over and over.

I would greatly appreciate any help. I've spent literal hours trying to figure out the problem on my own.

The main problem is use of globals. Delete the globals, delete unneded clear_foo() function, and your program works as you expect it to.

#include <iostream>
#include <string>
#include <sstream>

using namespace std;


string int_to_s(int, string&);
string cypher(string);

int main()
{
    string foo;
    int number = 123;

    cout << int_to_s(number, foo) << endl;;
    cout << int_to_s(456,foo) << endl;

    return 0;
}

//Defined Functions
/*This bit of code comes from various sources on the web
 *that say this is easiest way to convert int to str */
string int_to_s(int num, string& foo){
    stringstream toString;
    toString << num;
    foo = toString.str();
    return foo;
}

Thanks a lot! I knew the problem was going to be caused by something minorly stupid I did. Program works like a charm, thanks man :)

This article has been dead for over six months. Start a new discussion instead.