如何正确保存ofn.lpstrFile到字符串?

时间:2016-08-04 17:53:45

标签: c++ openfiledialog lpstr

您好我正在尝试为图像比较软件制作GUI。我们的想法是选择带有OPENFILENAME的图片,然后使用ofn.lpstrFile获取其地址,然后为该图像制作直方图。所以我用:

return(ofn.lpstrFile);

我可以cout地址或将其写入.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());

无法正常工作

1 个答案:

答案 0 :(得分: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使用NUL终止的C字符串。它通过查找末尾的零来知道字符串的长度。

std::string::size()并不总是一样的。我们可以调用resize来确保它们是同一个东西。

您不应该将\\替换为/。如果您的图书馆抱怨\\,请按以下方式替换:

示例:

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

使用std::cout检查输出,而不是猜测它是否有效。在Windows程序中,您可以使用OutputDebugStringMessageBox来查看字符串是什么。

HistCreation(path, root_dir);

我不知道root_dir应该是什么。如果HistCreation失败或参数错误,那么您会遇到其他问题。

相关问题