我有一个将 ppm 文件(图片格式)写入磁盘的功能。它将文件名作为 char* 数组。在我的主要功能中,我使用字符串流和 << 运算符组合了一个文件名。然后,我想将此结果传递给我的 ppm 函数。我在其他地方看到过这个讨论,通常使用非常复杂的方法(许多中间转换步骤)。
我所做的显示在下面的代码中,其他人通常在许多步骤中使用临时变量做的棘手部分是 (char*) (PPM_file_name.str().data())
。这完成的是使用 .str() 从 stringstream PPM_file_name 中提取字符串,然后使用 .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:
修改 write_ppm 以获取 const char*:
void write_ppm(const char *file_name, char *comment, unsigned char *image,int width,int height)
现在我按如下方式传递 ppm_file_name:
write_ppm((PPM_file_name.str().c_str()),"A comment",rgb_images[ccd_num],width,height);
这里有什么我应该做的吗,或者这是否主要解决了之前如何通过的问题? write_ppm 的所有其他 char 参数也应该是 const 吗?这是一个非常短的函数,而且似乎没有修改任何参数。谢谢。
关于c++ - 将 stringstream 的内容传递给以 char* 为参数的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4156770/