-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?

6
  • You forgot to tell us what the problem is. Commented Feb 8, 2013 at 16:33
  • There are dozens of SO questions on this already. stackoverflow.com/questions/5590381/… Commented Feb 8, 2013 at 16:33
  • 1
    std::to_string, Boost lexical_cast, ... Commented Feb 8, 2013 at 16:35
  • I said I want for example pass 5 to function but instead it pass 12345 this is the problem Commented Feb 8, 2013 at 16:37
  • 1
    @EYx: You need to stop saying "it doesn't work" and learn to be precise. Describe what happens. Apply some analytical thought! Because we are not psychic after 4pm. Commented Feb 8, 2013 at 16:40

2 Answers 2

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.)

Sign up to request clarification or add additional context in comments.

2 Comments

Good spot. I failed to parse the question at all.
yeah your first opinion worked!Tnx alot
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)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.