如何将ofn.lpstrFile保存为字符串?
嗨,我想为图像比较软件做一个图形用户界面。这个想法是选择一个带有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());
没工作,要么
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程序中,您可以使用OutputDebugString
或MessageBox
来查看字符串是什么。我不知道root_dir
应该是什么。如果HistCreation
失败或者它有错误的参数,那么你有一个不同的问题。
太棒了! @BarmakShemirani有一些变化,我现在开始工作。非常感谢我一整天都在为此工作。我将编辑你的文章到我现在的表格,以使答案更准确。 不错的工作人员谢谢你! –
我注释了一些建议的编辑。 'path.erase(path.begin()+ a,path.end());'什么都不做。字符串很好。 –
奇怪....如果我打印出路径,我看到这样的东西:C:/path/dir/image.jpgaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa。这就是为什么我使用earse –
使用'std :: wstring'来返回字符串。如果你不知道自己在做什么,返回指针是一个糟糕的主意。 –
你不是想要做*文件名*的直方图,是吗? – molbdnilo
感谢您的回应! @BarmakShemirani我尝试{wstring path = ofn.lpstrFile},但它说:没有合适的构造函数来从LPSTR转换为字符串,wchar,char,wchar_t可以更具体吗? –