字符串流到数组

发布于 2024-10-17 11:29:52 字数 362 浏览 13 评论 0原文

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

我有

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 为什么它是错误的并且不起作用?在第一次循环运行时,字符串流将正确的值设置为数组,但后来只有 0?

谢谢

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

不可一世的女人 2024-10-24 11:29:52

在使用 result.str("") 刷新字符串流之前,尝试使用 result.clear() 处理字符串流。这将其设置为输出缓冲区后再次接受输入的状态。

#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 的预期输出。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文