从 std::ostream 获取 char*
时间: 2023-09-10 20:06:24 浏览: 40
可以使用流插入运算符 "<<" 以及流对象的成员函数 str() 来获取 char*。例如:
```c++
std::ostringstream os;
os << "Hello world!";
std::string str = os.str();
const char* charPtr = str.c_str();
```
在上述代码中,我们使用 std::ostringstream 对象 os 来将字符串输出到流中,然后使用 str() 函数将流对象转化为 std::string 对象,最后使用 c_str() 函数获取 std::string 对象内部存储的 char* 指针。
相关问题
[Error] cannot bind 'std::ostream {aka std::basic_ostream<char>}' lvalue to 'std::basic_ostream<char>&&'
这个错误是因为尝试将一个左值绑定到一个右值引用上,具体来说是尝试将一个 std::ostream 对象绑定到一个 std::basic_ostream<char>&& 上。这通常发生在使用移动语义时,例如将一个 std::ostream 对象传递给一个接受右值引用的函数。解决方法是使用 std::move() 将左值转换为右值引用。
[Error] cannot bind ‘std::ostream {aka std::basic_ostream<char>}‘ l value To'std::basic_ostream<char>&&'
This error message means that you are trying to assign a value to an output stream (std::ostream) using an lvalue (an expression that refers to an object that has a memory address) but the type of the lvalue is not compatible with the type of the output stream.
For example, if you have the following code:
```cpp
int main() {
int x = 42;
std::ostream out;
out = x;
return 0;
}
```
You will get the error message because you cannot assign an integer value to an output stream. You need to use the insertion operator (<<) to write the value to the stream:
```cpp
int main() {
int x = 42;
std::ostream out;
out << x;
return 0;
}
```
This will write the value of x to the output stream.