Convert WCHAR[260] ) to std::string

Hi all,

Would you please help me to convert WCHAR[260] to std::string? Thanks!

Here is my code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
  int Listfilename(string DirSpec, string fspec)
{	
	int nfiles, len, BUFSIZE;
	nfiles = 0;
	BUFSIZE = 256;
	LPCWSTR  dir;
	dir = (LPCWSTR) malloc (BUFSIZE);
	WIN32_FIND_DATA FindFileData;
	HANDLE hFind = INVALID_HANDLE_VALUE;
	string filename;

	// Check that the input is not larger than allowed.
	if ( int( DirSpec.size() ) > ( BUFSIZE - 2) )
	{
		printf("Input directory is too large.\n");
		return 3;
	}
	cout << "Target directory is %s.\n" << DirSpec << endl;

	// Prepare string for use with FindFile functions.  First,
	// append '\*' to the directory name then copy the string.
	DirSpec += "\\*";
	len = MultiByteToWideChar(CP_ACP, 0, DirSpec.c_str(), DirSpec.size()+1, 0, 0);
	wchar_t* buf = new wchar_t[len];
	MultiByteToWideChar(CP_ACP, 0, DirSpec.c_str(), DirSpec.size()+1, buf, len);
	wstring r(buf);
	delete[] buf;
	dir = r.c_str();	

	// Find the first file in the directory.
	hFind = FindFirstFile(dir, &FindFileData);

	if (hFind != INVALID_HANDLE_VALUE)
	{
		do
		{
			filename = FindFileData.cFileName
			cout << filename << endl;
		}
		}while ( FindNextFile( hFind, &FindFileData ) );
		FindClose( hFind );
	}	
	return nfiles;
} 


The error message I got was "cannot convert WCHAR[260] ) to std::string". I want to convert "FindFileData.cFileName" to a std::string and save it into an array of string.

Bo
Last edited on
You could use WideCharToMultiByte funstion to produce a char array.
Then
1. use the array to create a std::string because std::string has a constructor for char*

OR

2. Use the std::string assignment operator because you can assign to a std::string from a char*


EDIT - Example (note - no error checking on WideCharToMultiByte function return shown) :
1
2
3
4
5
6
7
8
9
10
    //wide char array
    WCHAR wc[260] = L"Hello World";

    //convert from wide char to narrow char array
    char ch[260];
    char DefChar = ' ';
    WideCharToMultiByte(CP_ACP,0,wc,-1, ch,260,&DefChar, NULL);
    
    //A std:string  using the char* constructor.
    std::string ss(ch);
Last edited on
Thank you, guestgulkan. Your suggestion solved my problem!
Topic archived. No new replies allowed.