2011-02-12 33 views
2

你能告訴我,爲什麼這是錯的?stringstream到數組

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

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

當我看試陣 - 只有第一個 - 試驗[0] - 有正確的值 - 每一個其他測試[1..X]的值爲0 爲什麼它的錯,而不是加工?在循環的第一次運行中,stringstream將正確的值設置爲數組,但稍後只有0?

感謝

回答

3

嘗試result.clear()result.str("")沖洗之前,荷蘭國際集團的stringstream的。這會在輸出緩衝區後將其設置爲再次接受輸入的狀態。

#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; 
} 

沒有清除,我得到test[0] == 0test[1] == -832551553 /*some random number*/。與clear我得到預期的輸出test[0] == 0test[1] == 1