打印 Stringstream 输出指针

发布于 2024-11-15 21:03:39 字数 319 浏览 6 评论 0原文

下面的代码没有输出预期的“Bar”字符串,而是输出看起来像指针的内容。

#include <sstream>
#include <iostream>

int main()
{
    std::stringstream Foo("Bar");
    std::cout << Foo << std::endl; // Outputs "0x22fe80."
    return 0;
}

这可以通过使用 Foo.str() 来解决,但它过去给我带来了一些问题。是什么导致了这种奇怪的行为?它记录在哪里?

Rather than outputting the expected string of "Bar", the following code outputs what looks to be a pointer.

#include <sstream>
#include <iostream>

int main()
{
    std::stringstream Foo("Bar");
    std::cout << Foo << std::endl; // Outputs "0x22fe80."
    return 0;
}

This can be worked around by using Foo.str(), but it's caused some issues for me in the past. What causes this strange behavior? Where is it documented?

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

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

发布评论

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

评论(3

晨与橙与城 2024-11-22 21:03:39

这可以通过使用 Foo.str() 来解决,但它过去给我带来了一些问题。是什么导致了这种奇怪的行为?它记录在哪里?

这一点也不奇怪。

流就是流,不是字符串。

可以通过成员函数.str()获取[string]缓冲区。这不是一个解决方法:它是 API。它应该记录在您的 C++ 标准库参考中,如果没有,那么您的参考不完整/错误。

稍微奇怪的是,您得到的是内存地址而不是编译错误;这是由于在 pre-C++ 中使用了safe bool idiom 0x 标准库,如另一个答案中所述。)

This can be worked around by using Foo.str(), but it's caused some issues for me in the past. What causes this strange behavior? Where is it documented?

It's not strange at all.

A stream is a stream, not a string.

You can obtain the [string] buffer with the member function .str(). That's not a workaround: it's the API. It should be documented in your C++ standard library reference, and if it's not then your reference is incomplete/wrong.

(What is slightly strange is that you get a memory address rather than a compilation error; that is due to the use of the safe bool idiom in the pre-C++0x standard library, as covered in another answer.)

笑脸一如从前 2024-11-22 21:03:39

std::stringstream 不应插入流中。这就是为什么你有 str() 方法。

您观察到的行为是由于 std::stringstream 转换为 void*,这是用于测试流的:

if(Foo) { // this uses the conversion to void*
}

在 C+ 中+11,此转换被显式转换为 bool 所取代,这导致此代码无法编译:

std::cout << Foo << std::endl;

A std::stringstream is not supposed to be inserted in a stream. That's why you have the str() method.

The behavior you're observing is due to the fact that std::stringstream has a conversion to void*, which is what is used to test the stream:

if(Foo) { // this uses the conversion to void*
}

In C++11, this conversion is replaced by an explicit conversion to bool, which causes this code not to compile:

std::cout << Foo << std::endl;
很糊涂小朋友 2024-11-22 21:03:39

(1)使用 std::cout <<富<< std::endl;您应该确保 stringstream 已经重载“<<”。

(2)如果没有过载“<<” ,使用 std::cout <<富<< std::endl;可以输出 Foo 的地址。

(1)use std::cout << Foo << std::endl; you should make sure stringstream has already overload "<<".

(2)if there is not overload "<<" , use std::cout << Foo << std::endl; may output the Foo's address.

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