A problem with loops and Stringstreams

This is a discussion on A problem with loops and Stringstreams within the C++ Programming forums, part of the General Programming Boards category; Hi, I have the following code: Code: ostringstream temp; for(int i=2; i<x; i++) { if((x%i)==0) { hasFactors=1; temp << i ...

  1. #1
    Registered User
    Join Date
    Mar 2009
    Posts
    45

    A problem with loops and Stringstreams

    Hi, I have the following code:

    Code:
        ostringstream temp;
        
        for(int i=2; i<x; i++)
        {
                if((x%i)==0) {
                             hasFactors=1;
                             temp << i ;
                             output += temp.str(); 
                }
        }
    .

    It is designed to factorise the number x and display all the factors in the variable 'output'.

    But there is a trouble. Say 12 was the number for instance.

    You would expect output (which is a string btw) to equal "2346". Instead it equals

    "2 23 234 2346" without the spaces (I added them for clarity). Is there a way that I can get the effect that I want.

    Thanks in advance,
    mintsmike.

  2. #2
    The larch
    Join Date
    May 2006
    Posts
    3,573
    Don't add the contents of the stringstream (which keeps growing) to the output string at each iteration?
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21