-2

I have a function which accept a string parameter and I have an integer variable then I should convert it to string and then pass it to that function I used this code but as ostringstream is for I/O it doesn't work.

ostringstream ostr;
while (.....)
{
regnum++;
ostr<<regnum;
grph.addlastname(ostr.str());
}

for example it pass 12345 to function instead of 5,what should I do?

Elnaz Yousefi
  • 195
  • 1
  • 3
  • 17

2 Answers2

5

It's true - there are a lot of similar questions which solve "What's the best way to do this?" but I think that there's something to learn for the OP in the answer to the question of "Why does this not work?"

Therefore:

Your stringstream has an internal state, and during your loop you always append a new digit - but the previous ones are still in the stream! You can fix this by making the stringstream scope-local to the loop, i.e. declaring it inside the loop rather than outside of it.

(std::to_string is still the better solution for this particular problem, though.)

us2012
  • 16,083
  • 3
  • 46
  • 62
0

Everything is fine except one thing, see:

ostringstream ostr;
 while (.....)
{
 regnum++;
 ostr<<regnum;
 grph.addlastname(ostr.str());
}

Your declaring your ostr outside the while, the first time that while runs, it adds '1' to the ostr, the second time, because it's the same "ostringstream" variable, it adds '2', so your string will be '12' now...

Solution: Declare ostringstream ostr, inside your while, use std::to_string, or do a ostr.clear() every time that the while ends. (The best way si declaring your ostr inside your while)

Spamdark
  • 1,341
  • 2
  • 19
  • 38