我寫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