Question

I am trying to compare the file name against a list of strings to see if they match up and if they do then return accordingly

I am using the following condition:

if (strstr(file, str) != NULL) {
    return 1;
}

Though MSVC++2012 prompts me with the following error on strstr:

Error: no instance of overloaded function "strstr" matches the argument list
argument types are: (WCHAR [260], char *)

The question is: what is the meaning of the error above and how could it be fixed?

Was it helpful?

Solution

The problem you have got comes out from the fact that the strstr function expects to see two char pointers (char *) as its arguments, but it receives the WCHAR array instead as the first argument.

Unlike the usual 8-bit char, WCHAR represents a 16-bit Unicode character.

The one way to fix your error is to convert your Unicode file name to the char array as following:

char cfile[260];
char DefChar = ' ';
WideCharToMultiByte(CP_ACP, 0, file, -1, cfile, 260, &DefChar, NULL);

And then use cfile instead of file.

But this approach will only work with ASCII characters.

For that reason, you could consider using another string comparison method, suitable for the WCHAR strings (wstring).

The following code might help you with that second approach:

// Initialize the wstring for file
std::wstring wsfile (file);    

// Initialize the string for str
std::string sstr(str);

// Initialize the wstring for str
std::wstring wstr(sstr.begin(), sstr.end());

// Try to find the wstr in the wsfile
int index = wsfile.find(wstr); 

// Check if something was found
if(index != wstring::npos) {
    return 1;
}

The good SO answer about usage of the find method in std::wsting: Find method in std::wstring.

More on converting string to wstring: Mijalko: Convert std::string to std::wstring.

Please leave some feedback in comments if it does not help.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top