Viktor Bendik Viktor Bendik - 2 months ago 11x
C++ Question

How to save ofn.lpstrFile to string properly?

Hi i am trying to make a GUI for image compare software. The idea is to choose a picture with OPENFILENAME, then get its address with ofn.lpstrFile then make a histogram for that image. So i use:


I can cout the address or write it to an .xml file and the address is correct, but when i am trying to do the histogram it gives me all zeros. Behaves like the address was invalid.

Any ideas ?

my code :

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

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


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


I also tried

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

Did not work either


std::string returns the string and that's all you need. This is example to open a bitmap file.

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

std::string browse()
    std::string path(MAX_PATH, 0);
    OPENFILENAME ofn = { sizeof(OPENFILENAME) };
    ofn.lpstrFilter = "image files (*.jpg)\0*.jpg\0"; //changed from .bmp to .jpg
    ofn.lpstrFile = &path[0];
    ofn.nMaxFile = MAX_PATH;
    ofn.Flags = OFN_FILEMUSTEXIST;

    //string x = ofn.lpstrFile;
    //int a = x.size();
    //path.erase(path.begin() + a, path.end()); //earse the redundant characters from the address

    return path;

int main()
    std::string path = browse();
    std::replace(path.begin(), path.end(), '\\', '/');
    std::cout << path << "\n";
    return 0;

You shouldn't need to replace \\ with /. If your library complains about \\ then replace as follows:


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

Use std::cout to examine the output instead of guessing if it worked or not. In Windows program you can use OutputDebugString or MessageBox to see what the string is.

HistCreation(path, root_dir);

I don't know what root_dir is supposed to be. If HistCreation fails or it has the wrong parameter then you have a different problem.