附加作为空字符串的 ostream 可防止进一步追加



这个程序没有像我预期的那样工作。它输出"abc",但我期望"abcxyz"。将包含空字符串的流追加到流中,会导致流Pos 设置为 -1,并且无法向其追加更多数据。 我正在使用 C++ 的技术 - 将一个流中的数据发送到另一个流,但如果其中一个流碰巧为空,它不起作用。我曾认为在这种情况下 rdbuf(( 可能会返回nullptr,所以我检查了一下。它不是空的,但无论它返回什么,都不会让下游满意。注释掉该行:out << b.rdbuf();会导致它按预期输出"abcxyz"。附加可能恰好为空的数据流的正确方法是什么?

#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 = %qdn", (int64_t)out.tellp());
out << b.rdbuf();
printf("after B out.tellp = %qdn", (int64_t)out.tellp());
out << c.rdbuf();
printf("after C out.tellp = %qdn", (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;
}

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

下面是示例代码。在这里看到它的工作:

#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 = %qdn", (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 = %qdn", (int64_t)out.tellp());
out << c.rdbuf();
printf("after C out.tellp = %qdn", (int64_t)out.tellp());
std::cout << out.rdbuf() << std::endl;
return 0;
}

最新更新