Question

The code I wrote below figures the sum of the digits the given number consists of until sum > 10. So,the questions is: operator ">>" extracts the information from the stream and makes the stream empty ? If it's ,so why can't I perfom "ss<< sum" after I reset the bit of EOF to 0 ?

int sum = 0;
stringstream ss("13245");
char ch;
while (1)
{
    while (ss >> ch)
    {
        sum += ch - '0';
    }
    ss.clear();
    ss << sum; //can't perfom
    if (sum<10 ) break;
             sum=0;


}
cout << sum;
Was it helpful?

Solution 2

If you're trying to reset the stream with each iteration, this will likely do what you seek:

int sum = 0;
stringstream ss("13245");

while (1)
{
    int c;
    while ((c = ss.get()) != EOF)
        sum += c - '0';

    ss.clear(); // clear stream state
    ss.str(""); // clear buffer
    ss << sum;  // write new data

    if (sum<10 )
        break;

    sum=0;
}
cout << sum;

Output

6

Note: I took liberty to use the get() member, as it seemed more appropriate for what you were trying to accomplish. And tested with your 9999 aux sample also produces the expected 9 result. To answer your question, yes, the string buffer is not cleared unless you clear it (which we do above with str("")).

OTHER TIPS

Isn't your problem better solved with integer than with strings? Like:

#include <iostream>

template<typename SomeIntegralT>
SomeIntegralT sum_digits(SomeIntegralT n) {
    do {
        SomeIntegralT sum = 0;
        while( n ) {
            sum += n % 10;
            n /= 10;
        }
        n = sum;
    } while( n > 9 );
    return n;
}

int main()
{
    std::cout << sum_digits(124343525ul) << std::endl;
    std::cout << sum_digits(9999) << std::endl;
    std::cout << sum_digits(12345) << std::endl;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top