3

could you tell me, why is this wrong?

I have

mytype test[2];
stringsstream result;
int value;

for (int i=0; i<2; i++) {
   result.str("");
   (some calculating);
   result<< value;
   result>> test[i];
}

When I watch to test array - only first - test[0] - has correct value - every other test[1..x] has value 0 why its wrong and not working? in first run in cycle the stringstream set the correct value to array, but later there is only 0?

thanks

1 Answer 1

4

Try result.clear()ing your stringstream before flushing it with result.str(""). This sets it to a state of accepting inputs again after outputting the buffer.

#include <sstream>
using namespace std;

int main(){
    int test[2];
    stringstream result;
    int value;

    for (int i=0; i<2; i++) {
        result.clear();
        result.str("");
        value = i;
        result<< value;
        result>> test[i];
    }

    return 0;
}

Without clearing I get test[0] == 0 and test[1] == -832551553 /*some random number*/. With clear I get the expected output of test[0] == 0 and test[1] == 1.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.