2

I have one array of WCHAR is like this

WCHAR Path[256];

So I'm passing this array in my function getpath(Path) and It's filling the value in path like this:

//device/systemName/

So I want to get only device from above string.

My code is here:

   WCHAR *pDevName;

   int i = 0;
   int j = 0;

   while(Path[i] != NULL){ 
     if(0 ==(wcscmp(Path, L"/")))
     {

        //i = i + 2;
         ++i;
        continue;
    }

    else
    {
        pDevName[j] = Path[i];

        ++i;
        ++j;
        if (0 == wcscmp(Path, L"/")){
            break;
        }
    }

My code is getting compiled but it's not returning for me device from WCHAR array. It's returning //devicename/systemName/, which is coming from pDevName.

I have doubt over my comparison on wcscmp(). So my question is how to compare / with remaining wchar array value.

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
Vikas Sharma
  • 33
  • 1
  • 4

2 Answers2

1

wcscmp compares a string, not a character. You're also passing the same address to wcscmp every time - Path, which means all you're doing is comparing the whole string against "/", which will always fail.

If you want to test a single character you can simply compare its value directly, for example:

WCHAR *pDevName;
// NB: I assume you are allocating pDevName and just left that out of the code
// for brevity.
int i = 0;
int j = 0;

while(Path[i] != L'\0'){ 
 if(Path[i] == L'/')
 {
     ++i;
    continue;
 }
 else
 {
    // NB: you should check for overflow of pDevName here
    pDevName[j++] = Path[i++];
    if (Path[i] == L'/')
        break;
 }
}
Jonathan Potter
  • 36,172
  • 4
  • 64
  • 79
1

Since you specified c++, it would be easier to do something like this:

#include <string>

using namespace std;

wstring get_device_name(const wchar_t* path) 
{
    wstring source(path);
    wstring device_name;

    if (source.substr(0, 2)==L"//") 
    {
        size_t position= source.find(L'/', 2);

        if (position==wstring::npos) 
            device_name= source.substr(2);
        else
            device_name= source.substr(2, position-2);
    }

    return device_name;
}
pagra
  • 665
  • 4
  • 11