views:

407

answers:

4

Hi below is my function:

string Employee::get_print(void) {

   string out_string;
   stringstream ss;

   ss << e_id << " " << type << endl;
   out_string = ss.str();

   return out_string;
}

e_id and type are int and they contain values from the class Employee. But when I pass them into the stringstream they just clear the string when I try to out put it. But if I don't have a int in the ss << "Some text" << endl; this output fine. What am I doing wrong =S

//Edit

Ok; This is the calling code:

tmp = cur->get_print();

Where tmp is a string and cur is an Employee Object.

This code...

stringstream out; 
out << "Test " << e_id << " " << e_type; 
return out.str(); 

Retruns "Test " and nothing else. If I take out "Test " << my returned string is ""

I'm using GCC 4.2 on Mac OS/X 10.6.2 if that makes any difference.

A: 

I think the endl is not needed. You only need to write endl if you want to write a newline on a file on on std::cout.

Since you write endl, your stringstream will contain a string with 2 lines of which the second is empty. This probably confuses you. Remove the endl to get only one line.

Patrick
+1  A: 

I too am unable to reproduce this error. As has been mentioned, don't include the endl, as this actually appends a \n and is supposed to flush the write buffer. For this use, it is completely unnecessary and may actually lead to undesirable results...However, the code in your edit/update works just fine for me.

int main(int argc, char* argv[])
{
   int e_id = 5;
   int e_type = 123456;
   stringstream out; 
   out << "Test " << e_id << " " << e_type;
   cout << out.str();
   return 0;
}

Produces:

Test 5 123456

My suggestions would be to double check that e_id and e_type are really just native int.

For further testing, you may want to force a cast on the values to see if it helps as such:

out << "Test " << (int)e_id << " " << (int)e_type;

Since I'm unable to reproduce this error, I'm afraid I'm unable to help any further. But best of luck to you!

KevenK
+1  A: 

Ok I have no idea what is going on with stringstream I've tried using it in other parts of my code and it doesn't work with integers. Therefore, I have reverted to using the sprintf C function:

string Employee::get_print(void) {

   char out[50];

   sprintf(out, "%d %d", e_id, e_type);

   string output = out;

   return output;
} 

This returns the string which is needed.

jumm
Once again, the variable `output` is redundant. Also, I don’t think it’s a good idea that you mask a bug somewhere in your application by avoiding the symptoms. Your initial code was fine. If it produced wrong results this means that there’s a bug *somewhere else*. Your change didn’t fix that bug.
Konrad Rudolph
It was a bug with Xcode, it works fine with NetBeans. (using stringstream)
jumm
A: 

I have moved into Netbeans and I don't have this problem. So it is an issue with Xcode.

jumm