2016-08-04 190 views
0

嗨,我想爲圖像比較軟件做一個圖形用戶界面。這個想法是選擇一個帶有OPENFILENAME的圖片,然後用ofn.lpstrFile獲取它的地址,然後爲該圖像創建一個直方圖。所以我用:如何將ofn.lpstrFile保存爲字符串?

return(ofn.lpstrFile); 

我可以清點地址或將其寫入到一個.xml文件,地址是正確的,但是當我試圖做到這一點給了我全部爲零的直方圖。表現得像地址是無效的。

任何想法?

我的代碼:

string path=browse(); //getting the string from ofn.lpstrFile 

    path.c_str(); 
    replace(path.begin(), path.end(), '\\', '/'); //converting backslash to slash also may be the problem  
    HistCreation(path,root_dir); 

void HistCreation(string path,string root_dir) { 

Mat img; 
img = imread(path); // here if i manually enter the address everything works fine, if I insert the path then loads empty image 

. 
. 
. 

我也試過

char * cstr = new char[path.length() + 1]; 
    std::strcpy(cstr, path.c_str()); 

沒工作,要麼

+2

使用'std :: wstring'來返回字符串。如果你不知道自己在做什麼,返回指針是一個糟糕的主意。 –

+0

你不是想要做*文件名*的直方圖,是嗎? – molbdnilo

+0

感謝您的迴應! @BarmakShemirani我嘗試{wstring path = ofn.lpstrFile},但它說:沒有合適的構造函數來從LPSTR轉換爲字符串,wchar,char,wchar_t可以更具體嗎? –

回答

0

std::string返回字符串,這就是你甲腎上腺素編輯。這是打開一個位圖文件的例子。

(編輯)

#include <iostream> 
#include <string> 
#include <windows.h> 

std::string browse(HWND hwnd) 
{ 
    std::string path(MAX_PATH, '\0'); 
    OPENFILENAME ofn = { sizeof(OPENFILENAME) }; 
    ofn.hwndOwner = hwnd; 
    ofn.lpstrFilter = 
     "Image files (*.jpg;*.png;*.bmp)\0*.jpg;*.png;*.bmp\0" 
     "All files\0*.*\0"; 
    ofn.lpstrFile = &path[0]; 
    ofn.nMaxFile = MAX_PATH; 
    ofn.Flags = OFN_FILEMUSTEXIST; 
    if (GetOpenFileName(&ofn)) 
    { 
     //string::size() is still MAX_PATH 
     //strlen is the actual string size (not including the null-terminator) 
     //update size: 
     path.resize(strlen(path.c_str())); 
    } 
    return path; 
} 

int main() 
{ 
    std::string path = browse(0); 
    int len = strlen(path.c_str()); 
    if (len) 
     std::cout << path.c_str() << "\n"; 
    return 0; 
} 

注意,Windows使用NULL結尾的C字符串。它通過在末尾查找零來知道字符串的長度。

std::string::size()並不總是一回事。我們可以調用調整大小以確保它們是相同的東西。


你不應該需要/更換\\。如果庫抱怨\\然後替換如下:

例子:

... 
#include <algorithm> 
... 
std::replace(path.begin(), path.end(), '\\', '/'); 

使用std::cout檢查,而不是猜測的輸出,如果它的工作與否。在Windows程序中,您可以使用OutputDebugStringMessageBox來查看字符串是什麼。我不知道root_dir應該是什麼。如果HistCreation失敗或者它有錯誤的參數,那麼你有一個不同的問題。

+0

太棒了! @BarmakShemirani有一些變化,我現在開始工作。非常感謝我一整天都在爲此工作。我將編輯你的文章到我現在的表格,以使答案更準確。 不錯的工作人員謝謝你! –

+0

我註釋了一些建議的編輯。 'path.erase(path.begin()+ a,path.end());'什麼都不做。字符串很好。 –

+0

奇怪....如果我打印出路徑,我看到這樣的東西:C:/path/dir/image.jpgaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa。這就是爲什麼我使用earse –