追加一个为空字符串的ostream可以防止进一步追加

问题描述 投票:0回答:1

此程序无法正常运行。它输出“ abc”,但我期望“ abcxyz”。将包含空字符串的流添加到流中,将导致streampos设置为-1,并且无法再向其添加任何数据。我使用的是C++ - Send data in one ostream to another ostream中的技术,但是如果其中一个流恰好是空的,则它不起作用。我以为在这种情况下rdbuf()返回nullptr,所以我检查了一下。它不是null,但是返回的任何内容都不会使下游满意。注释掉该行:out << b.rdbuf();使它按预期输出“ abcxyz”。追加可能偶然为空的ostream的正确方法是什么?

#include <iostream>
#include <sstream>

int main(int argc, const char * argv[]) {
    std::stringstream a, b, c, out;

    a << "abc";
    b << "";
    c << "xyz";

    out << a.rdbuf();
                printf("after A out.tellp = %qd\n", (int64_t)out.tellp());
    out << b.rdbuf();
                printf("after B out.tellp = %qd\n", (int64_t)out.tellp());
    out << c.rdbuf();
                printf("after C out.tellp = %qd\n", (int64_t)out.tellp());

    std::cout << out.rdbuf() << std::endl;

    return 0;
}

输出为:

after A out.tellp = 3
after B out.tellp = -1
after C out.tellp = -1
abc
Program ended with exit code: 0

编辑:固定版本。有更好的方法吗?

#include <iostream>
#include <sstream>

template <class T, class U>
void append(T& a, U& b) 
{
    if (int64_t(b.tellp()) <= 0) return;
    a << b.rdbuf();
}

int main(int argc, const char * argv[]) {
    std::stringstream a, b, c;

    a << "abc";
    b << "";
    c << "xyz";

    append(std::cout, a);
    append(std::cout, b);
    append(std::cout, c);
    std::cout << std::endl;

    return 0;
}
c++ append ostream
1个回答
0
投票

您可以使用std::basic_ios::good()std::basic_ios::clear()实现您想要的目标。

下面是示例代码。参见it working here

#include <iostream>
#include <sstream>

int main(int argc, const char * argv[]) 
{
    std::stringstream a;
    std::stringstream b;
    std::stringstream c;
    std::stringstream out;

    a << "abc";
    b << "";
    c << "xyz";

    out << a.rdbuf();
    printf("after A out.tellp = %qd\n", (int64_t)out.tellp());

    out << b.rdbuf();
    if( ! out.good() )
    {
        std::cout<< "It is not good!!!" << std::endl;
        out.clear();
    }
    printf("after B out.tellp = %qd\n", (int64_t)out.tellp());

    out << c.rdbuf();
    printf("after C out.tellp = %qd\n", (int64_t)out.tellp());

    std::cout << out.rdbuf() << std::endl;

    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.