我的问题可以归结为,字符串从stringstream.str().c_str()内存中返回的字符串在哪里,为什么不能将其分配给const char*?
这个代码示例将比我更好地解释它
#include <string>
#include <sstream>
#include <iostream>
using namespace std;
int main()
{
stringstream ss("this is a string\n");
string str(ss.str());
const char* cstr1 = str.c_str();
const char* cstr2 = ss.str().c_str();
cout << cstr1 // Prints correctly
<< cstr2; // ERROR, prints out garbage
system("PAUSE");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
stringstream.str().c_str()可以分配给a 的假设const char*导致我花了一段时间追踪的错误.
对于奖励积分,任何人都可以解释为什么替换cout声明
cout << cstr // Prints correctly
<< ss.str().c_str() // Prints correctly
<< cstr2; // Prints correctly (???)
Run Code Online (Sandbox Code Playgroud)
正确打印字符串? …
我正在使用Boost FileSystem 3遍历目录中的某些文件,并且需要将文件名转换为另一个库的char *,不幸的是我缺少C ++ foo,有人可以帮忙吗?
int main(int argc, char* argv[])
{
path p (argv[1]); // p reads clearer than argv[1] in the following code
try
{
if (exists(p)) // does p actually exist?
{
if (is_regular_file(p)) // is p a regular file?
cout << p << " size is " << file_size(p) << '\n';
else if (is_directory(p)) // is p a directory?
{
cout << p << " is a directory containing:\n";
typedef vector<path> vec; // store paths,
vec …Run Code Online (Sandbox Code Playgroud)