stringstream to array
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 开发者_C百科stringstream set the correct value to array, but later there is only 0?
thanks
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
.
精彩评论