gpt4 book ai didi

c++ - 如何通过 stdstring 打印 ostream 变量的值?

转载 作者:太空宇宙 更新时间:2023-11-04 12:47:20 25 4
gpt4 key购买 nike

我尝试通过转换为字符串来打印 ostream 变量中存在的值,然后打印字符串而不是 ostream 参数。
但它不起作用。

这是我的代码:

#include <iostream>
#include <cassert>
#include <cstring>
#include <sstream>

using std::ostream;

typedef std::basic_stringstream<char> stringstream;
class X {
public:
int y;
};

std::ostream& operator<<(std::ostream& os, const X x) {
return os << x.y;
}

int main() {
X x;
x.y = 5;

stringstream ss;
ostream output(nullptr);
output << x;
ss << output.rdbuf();
std::string myString = ss.str();

std::cout << x << std::endl; // 5
std::cout << "myString.c_str() :" << std::endl;
std::cout << myString.c_str() << std::endl; // nothing.
}

我该如何解决这个问题,才能到达 myString.c_str()合适的输出?

std::cout << myString.c_str() << std::endl; 中的输出行是 ""(空字符串 - 什么都没有),我希望它是 5也是(即 output 类型的 char* )..

最佳答案

引自 http://www.cplusplus.com/reference/fstream/ofstream/rdbuf/

std::ofstream::rdbuf

Returns a pointer to the internal filebuf object.

Notice however, that this is not necessarily the same as the currently associated stream buffer (returned by ios::rdbuf).

关于c++ - 如何通过 stdstring 打印 ostream 变量的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50782912/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com