5

How can I split a TCHAR into other variables? Example:

TCHAR comando[50], arg1[50], arg2[50];
Mensagem msg;
_tcscpy(msg.texto, TEXT("MOVE 10 12"));

So, msg.texto has the string "MOVE 10 12" and I want the variable comando[50] to be "MOVE", the variable arg1 to be "10" and the variable arg2 to be "12". How can I do that? Sorry for some possible English mistakes. Thanks in advance!

SOLVED:

TCHAR *pch;
    pch = _wcstok(msg.texto, " ");
        _tcscpy(comando, pch);
        pch = _wcstok(NULL, " ");
        _tcscpy(arg1, pch);
        pch = _wcstok(NULL, " ");
        _tcscpy(arg2, pch);
Andrew Truckle
  • 17,769
  • 16
  • 66
  • 164
user3088049
  • 91
  • 1
  • 8

2 Answers2

3

For TCHAR, you could use strtok, like in this example:

#include <stdio.h>
#include <string.h>

typedef char TCHAR;

int main ()
{
  TCHAR str[] ="MOVE 10 12";
  TCHAR * pch;
  printf ("Splitting string \"%s\" into tokens:\n",str);
  pch = strtok (str," ");
  while (pch != NULL)
  {
    printf ("%s\n",pch);
    pch = strtok (NULL, " ");
  }
  return 0;
}

In case it is a wchar_t, then you could use wcstok():

wchar_t *wcstok( wchar_t *strToken, const wchar_t *strDelimit );

Andrew Truckle
  • 17,769
  • 16
  • 66
  • 164
gsamaras
  • 71,951
  • 46
  • 188
  • 305
  • As I recall, `TCHAR` may be either `char` or `wchar_t` -- more commonly the latter. `strtok` does not work on arrays of `wchar_t`. (I don't remember whether there's a corresponding function that operates on wide strings.) – Keith Thompson May 14 '16 at 22:13
  • @KeithThompson thanks for justifying your downvote. Many people don't! Please see the comments under the question, where I asked the OP about it. He answered with this [link](https://msdn.microsoft.com/en-us/library/office/cc842072.aspx). However, if you would like to propose how I could improve my answer, please let me know! – gsamaras May 14 '16 at 22:15
  • @gsmaras thanks for your help but that doesn't work. – user3088049 May 14 '16 at 22:21
  • @user3088049 same for `wcstok()`? – gsamaras May 14 '16 at 22:22
  • 1
    Did a litle adjustments and it's working, thank you! – user3088049 May 14 '16 at 22:27
  • @gsamaras I already put it in my answer and accept your answer as the right one – user3088049 May 14 '16 at 22:30
1

To use the version agnostic, you should use _tcstok.

Andrew Truckle
  • 17,769
  • 16
  • 66
  • 164