3

你能告诉我,为什么这是错的?

我有

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

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

当我观看测试数组时 - 只有第一个 - test[0] - 具有正确的值 - 其他每个 test[1..x] 的值为 0 为什么它错误且不起作用?在第一次循环运行时,stringstream 将正确的值设置为数组,但后来只有 0?

谢谢

4

1 回答 1

4

result.clear()result.str(""). 这会将其设置为在输出缓冲区后再次接受输入的状态。

#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] == 0输出test[1] == 1

于 2011-02-12T11:30:06.907 回答