1

I'm trying to split a WideChar String in to an array, Here is the way I'm doing this :<>

WCHAR* Message = _T("This is a sample text"):
wchar_t *pwc;
CStringArray Command;
pwc = wcstok(Message, L" ");
int Count = 0;
while (pwc != NULL) {
    pwc = wcstok(NULL, L" ");
    Command.Add(pwc);
    Count++;
}

for (int i = 0 ; i <= Count ; i++)
{
    AfxMessageBox(Command[i]);
}

The problem is I do not have "This" in my final result array
Whats wrong ?

Shahriyar
  • 1,483
  • 4
  • 24
  • 37
  • Where's the array? You're just printing tokens. – Alan Stokes Sep 29 '13 at 13:37
  • Works for me (once I've fixed up the code to compile in a Linux environment, but that's wcstok() taking a third parameter to allow reentrancy, shouldn't change the behaviour. You are talking of an "array", which makes me think you are perhaps doing something wrong in your copying of the elements out of the string? – Mats Petersson Sep 29 '13 at 13:40
  • I'm adding tokens to CStringArray (CStringArray::Add) – Shahriyar Sep 29 '13 at 13:45
  • I have edited the question and changed the code to what Im currently using – Shahriyar Sep 29 '13 at 13:47
  • If you'd run the code you originally showed us you'd have seen it working - which might have helped you work out why this version doesn't. – Alan Stokes Sep 29 '13 at 13:57

2 Answers2

2

You need to move the call to Command.Add before the assignment to pwc in the loop - as it stands you're moving on to the second token before doing your first Add.

Alan Stokes
  • 18,815
  • 3
  • 45
  • 64
1

I am having no issues with your source. All string components are printing perfectly.

Here's my full working code:

#include "stdafx.h"
#include <wchar.h>

int main(int argc, char *argv[])
{
    wchar_t wcs[] = L"This is a sample string";
    wchar_t *pwc;
    pwc = wcstok(wcs, L" ");
    while (pwc != NULL) {
        wprintf(L"%ls\n", pwc);
        pwc = wcstok(NULL, L" ");
    }
}
Steve
  • 486
  • 2
  • 8
  • 19