我写PPM文件(图片格式)到磁盘的功能。它将文件名作为char *数组。在我的主要功能中,我使用stringstream和运算符将一个文件名放在一起。然后,我想将这个结果传递给我的ppm函数。我已经在其他地方看到过这种情况,通常看起来非常复杂的方法(许多转换步骤之间)。传递内容的功能采取的char *作为参数
我所做显示在下面的代码,而棘手的部分,其他人通常做的许多步骤与临时变量是(char*) (PPM_file_name.str().data())
。这样做的目的是从stringstream PPM_file_name中以.str()提取字符串,然后用.data()(这是一个const char *)获得指向其实际内容的指针,然后将其转换为常规(char *)。下面更完整的例子。
到目前为止,我发现以下工作很好,但它让我感到不安,因为通常当其他人以看似更复杂的方式完成某件事情时,这是因为这是一种更安全的方法。那么,任何人都可以告诉我,我在这里做的事情是安全的吗?
谢谢。
#include <iostream>
#include <sstream>
#include <stdio.h>
#include <string>
using namespace std;
int main(int argc, char *argv[]){
// String stream to hold the file name so I can create it from a series of other variable
stringstream PPM_file_name;
// ... a bunch of other code where int ccd_num and string cur_id_str are created and initialized
// Assemble the file name
PPM_file_name << "ccd" << ccd_num << "_" << cur_id_str << ".ppm";
// From PPM_file_name, extract its string, then the const char* pointer to that string's data, then cast that to char*
write_ppm((char*)(PPM_file_name.str().data()),"ladybug_vidcapture.cpp",rgb_images[ccd_num],width,height);
return 0;
}
你真的改变了write_ppm的文件名吗? – 2010-11-11 16:43:48
我建议在这里使用'const_cast'而不是'(char *)',只是为了清楚你的意图。 –
2010-11-11 16:48:13
如果你正在处理字符串,你应该使用c_str()而不是data()来访问std :: string对象。 c_str()附加一个空字符,data()不附加。 – badgerr 2010-11-11 16:53:49